package com.android.launcher3;

import static android.util.Log.d;
import static android.util.Log.e;
import static android.util.Log.w;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.app.Activity;
import android.app.ActivityGroup;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.app.StatusBarManager;
import android.app.WallpaperInfo;
import android.app.WallpaperManager;
import android.appwidget.AppWidgetHostView;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.Intent.ShortcutIconResource;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.IPackageDeleteObserver;
import android.content.pm.LabeledIntent;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.preference.PreferenceManager;
import android.provider.LiveFolders;
import android.text.Selection;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.method.TextKeyListener;
import android.util.Log;
import android.util.SparseArray;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Default launcher application.
 */
public final class Launcher extends ActivityGroup implements
		View.OnClickListener, View.OnLongClickListener, LauncherModel.Callbacks {

	static final boolean LOGD = false;
	static final String TAG = "Launcher";

	private static final boolean PROFILE_STARTUP = false;
	private static final boolean PROFILE_DRAWER = false;
	private static final boolean PROFILE_ROTATE = false;
	private static final boolean DEBUG_USER_INTERFACE = false;

	static boolean USE_MAINMENU_LISTMODE = true;

	private static final int ADDWIDGET_APPWIDGET = 2;
	private static final int ADDWIDGET_NONE = 0;
	private static final int ADDWIDGET_SAMSUNGWIDGET = 3;
	private static final int ADDWIDGET_SEARCH = 1;

	private static final int MENU_ADD = 2;
	private static final int MENU_WALLPAPER_SETTINGS = 3;
	private static final int MENU_SEARCH = 4;
	private static final int MENU_DESKTOP_SET = 200;
	private static final int MENU_NOTIFICATIONS = 5;
	private static final int MENU_CONTACTS = 6;
	private static final int MENU_SETTINGS = 7;
	private static final int MENU_MENUEDIT = 8;
	private static final int MENU_LISTVIEW = 9;
	private static final int MENU_GRIDVIEW = 10;
	private static final int MENU_SAVE = 11;
	private static final int MENU_DISCARD = 12;
	private static final int MENU_QUICKVIEW_WORKSPACE = 13;
	private static final int MENU_QUICKVIEW_MAINMENU = 14;
	private static final int MENU_GROUP_DEFAULT = 0;
	private static final int MENU_GROUP_ADD = 1;
	private static final int MENU_GROUP_DEFAULT_MENU = 2;
	private static final int MENU_GROUP_LIST_MENU = 3;
	private static final int MENU_GROUP_EDIT_MENU = 4;
	private static final int MENU_GROUP_HOMESCREEN_EDIT_MENU = 5;

	static boolean USE_MAINMENU_CONCENTRATION_EFFECT = false;

	private static final int REQUEST_CREATE_SHORTCUT = 1;
	private static final int REQUEST_CREATE_LIVE_FOLDER = 4;
	private static final int REQUEST_CREATE_APPWIDGET = 5;
	private static final int REQUEST_PICK_APPLICATION = 6;
	private static final int REQUEST_PICK_SHORTCUT = 7;
	private static final int REQUEST_PICK_LIVE_FOLDER = 8;
	private static final int REQUEST_PICK_APPWIDGET = 9;
	private static final int REQUEST_PICK_WALLPAPER = 10;
	private static final int DIALOG_CREATE_SHORTCUT = 1;

	static final int DIALOG_RENAME_FOLDER = 2;
	static final int DIALOG_DELETE_APPLICATION = 4;
	static final int DIALOG_DISCARD_MENUEDIT = 5;
	static final int DIALOG_DELETE_WORKSCREEN = 6;

	static final String EXTRA_SHORTCUT_DUPLICATE = "duplicate";
	static final String EXTRA_CUSTOM_WIDGET = "custom_widget";

	static final String SEARCH_WIDGET = "search_widget";
	static final int WALLPAPER_SCREENS_SPAN = 2;
	static int SCREEN_COUNT = 7;
	static final int DEFAULT_SCREN = 3;
	static int NUMBER_CELLS_X;
	static int NUMBER_CELLS_Y;
	static int DEFAULT_SCREEN_COUNT = 7;

	private static final String PREFERENCES = "launcher.preferences";
	private static final String PREFERENCES_CURRENTSCREEN = "currentscreen";
	private static final String PREFERENCES_LAUNCHER = "launcher";
	private static final String PREFERENCES_MENUMODE = "menu";
	private static final String PREFERENCES_SCREENCOUNT = "screencount";

	private static final String RUNTIME_STATE_CURRENT_SCREEN = "launcher.current_screen";
	private static final String RUNTIME_STATE_ALL_APPS_FOLDER = "launcher.all_apps_folder";
	private static final String RUNTIME_STATE_USER_FOLDERS = "launcher.user_folder";
	private static final String RUNTIME_STATE_PENDING_ADD_SCREEN = "launcher.add_screen";
	private static final String RUNTIME_STATE_PENDING_ADD_CELL_X = "launcher.add_cellX";
	private static final String RUNTIME_STATE_PENDING_ADD_CELL_Y = "launcher.add_cellY";
	private static final String RUNTIME_STATE_PENDING_ADD_SPAN_X = "launcher.add_spanX";
	private static final String RUNTIME_STATE_PENDING_ADD_SPAN_Y = "launcher.add_spanY";
	private static final String RUNTIME_STATE_PENDING_ADD_COUNT_X = "launcher.add_countX";
	private static final String RUNTIME_STATE_PENDING_ADD_COUNT_Y = "launcher.add_countY";
	private static final String RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS = "launcher.add_occupied_cells";
	private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME = "launcher.rename_folder";
	private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME_ID = "launcher.rename_folder_id";
	private static final String RUNTIME_STATE_DELETE_APPLICATION = "launcher.delete_application";
	private static final String RUNTIME_STATE_DELETE_WORKSCREEN_INDEX = "launcher.delete_index";
	private static final String RUNTIME_STATE_MENU_CURRENT_MODE = "launcher.menu_mode";
	private static final String RUNTIME_STATE_MENU_CURRENT_SCREEN = "launcher.menu_current_screen";
	private static final String RUNTIME_STATE_MENU_SCREEN_COUNT = "launcher.menu_screen_count";
	private static final String RUNTIME_STATE_QUICK_NAVIGATION = "launcher.quick_navigation";

	private static final Object sLock = new Object();
	private static int sScreen = DEFAULT_SCREN;
	static final int APPWIDGET_HOST_ID = 1024;
	public static final int SUCCEEDED = 1;
	static String mUninstallPackageName;
	public static Bitmap mMenuWallpaperBitmap;

	// private final BroadcastReceiver mReceiver;
	private static HashMap<Long, FolderInfo> mFolders = new HashMap<Long, FolderInfo>();

	private LauncherModel mModel = null;
	private OptionMenu optionMenu;

	private final BroadcastReceiver mCloseSystemDialogsReceiver = new CloseSystemDialogsIntentReceiver();

	private final BroadcastReceiver mWallpaperChangedReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String str = intent.getAction();

			if (Intent.ACTION_WALLPAPER_CHANGED.equals(str)) {
				Log.i("Launcher", "ACTION_WALLPAPER_CHANGED broadcast received");
				// if (Launcher.access$200(this.this$0)){
				updateWindowTransparency();
				// }
			}
		}
	};

	private final ContentObserver mWidgetObserver = new AppWidgetResetObserver();
	private LayoutInflater mInflater;
	private DragLayer mDragLayer;
	private Workspace mWorkspace;
	private AppWidgetManager mAppWidgetManager;
	private LauncherAppWidgetHost mAppWidgetHost;
	private CellLayout.CellInfo mAddItemCellInfo;
	private CellLayout.CellInfo mMenuAddInfo;
	private final int[] mCellCoordinates = new int[2];
	private FolderInfo mFolderInfo;
	private ExecutorService mExec;
	private boolean mIsActive;
	private boolean mIsMoveDefaultScreen;
	private boolean mDesktopLocked = true;
	private Bundle mSavedState;
	private boolean mIsScreenOff;
	private SpannableStringBuilder mDefaultKeySsb = null;
	private boolean mDestroyed;
	private boolean mIsNewIntent;
	private boolean mRestoring;
	private boolean mWaitingForResult;
	private boolean mLocaleChanged;
	private Bundle mSavedInstanceState;
	// private DesktopBinder mBinder;
	private MenuDrawer mMenuDrawer;
	private MenuManager mMenuManager;
	private boolean mMainMenuLoading = true;
	private int mStateQuickNavigation = -1;
	private AppShortcutZone mAppShortcutZone;
	private int mAddWidgetType;
	int[] mBlankScreen = new int[2];
	private WidgetPreview mWidgetPreview;
	private QuickViewWorkspace mQuickViewWorkspace;
	// private QuickViewMainMenu mQuickViewMainMenu;
	private SharedPreferences mPrefs;
	private int mMenuScreenCount = -1;
	private DeleteZone mDeleteZone;
	// private WallpaperCanvasView mWallpaperCanvasView;
	private Drawable mDimWallpaperImageDrawable;
	private Drawable mWallpaperImageDrawable;
	private boolean mForce16BitWindow;
	private IconCache mIconCache;
	private boolean mIsOpaqueWindow;
	private ArrayList<ItemInfo> mDesktopItems = new ArrayList<ItemInfo>();
	private boolean mIsDeletePopup;
	private boolean mWorkspaceLoading;
	private int mWidgetId;
	private AppWidgetProviderInfo mAppWidgetInfo;
	private LauncherAppWidgetInfo mLauncherAppWidgetInfo;
	private int[] mSpans = new int[2];
	private Toast mToast;
	private int mDeleteIndex = -1;
	private ProgressDialog mDialog;

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1: {
				// if (msg.arg1 == 1) {
				// // Log.e(LOG_TAG, "uninstall succeeded");
				// } else {
				// // Log.e(LOG_TAG, "uninstall failed");
				// }
				Launcher.this.mMenuManager.unlock();
			}

			case 2: {
			}

			default:
				return;
			}

			// if (paramMessage.arg1 == 1)
			// int i = Log.w("Launcher", "uninstall succeeded");
			// while (true)
			// {
			// Launcher.access$3100(this.this$0).unlock();
			// break;
			//
			// }
			// if (!this.this$0.isDefaultIMEI())
			// continue;
			// Launcher.access$3200(this.this$0);
		};
	};

	private boolean mConfigChange;
	static private int mLastOrientation = -123;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Log.e(TAG, "onCreate");

		this.mPrefs = getSharedPreferences(PREFERENCES_LAUNCHER,
				Context.MODE_PRIVATE);

		LauncherApplication localLauncherApplication = (LauncherApplication) getApplication();
		mModel = localLauncherApplication.setLauncher(this);

		this.mIconCache = localLauncherApplication.getIconCache();

		if (this.getResources().getConfiguration().orientation != mLastOrientation) {
			mLastOrientation = this.getResources().getConfiguration().orientation;
			this.mIconCache.flush();
			com.android.launcher3.Utilities.reset();
			// Log.e(TAG,"flush ");
		}

		mInflater = getLayoutInflater();
		mAppWidgetManager = AppWidgetManager.getInstance(this);

		mAppWidgetHost = new LauncherAppWidgetHost(this, APPWIDGET_HOST_ID);
		mAppWidgetHost.startListening();

		// if (PROFILE_STARTUP) {
		// android.os.Debug.startMethodTracing("/sdcard/launcher");
		// }

		SCREEN_COUNT = LauncherConfig.getScreenCount(this);
		DEFAULT_SCREEN_COUNT = LauncherConfig.getDefaultScreenCount(this);
		USE_MAINMENU_CONCENTRATION_EFFECT = LauncherConfig
				.getUseMainMenuConcentrationEffect(this);
		USE_MAINMENU_LISTMODE = LauncherConfig.getUseMainMenuListMode(this);
		NUMBER_CELLS_X = LauncherConfig.getWorkspaceCellsX(this);
		NUMBER_CELLS_Y = LauncherConfig.getWorkspaceCellsY(this);

		this.mForce16BitWindow = LauncherConfig.getUse16BitWindow(this);
		USE_MAINMENU_CONCENTRATION_EFFECT = LauncherConfig
				.getUseMainMenuConcentrationEffect(this);
		checkForLocaleChange();
		setWallpaperDimension();

		setContentView(R.layout.launcher);
		setupViews();

		registerIntentReceivers();
		registerContentObservers();

		mSavedState = savedInstanceState;
		restoreState(mSavedState);

		// this.mWallpaperCanvasView = new WallpaperCanvasView(this);
		// mWallpaperCanvasView.setWorkspace(mWorkspace);
		// this.mWallpaperCanvasView.setId(R.id.wallpaperCanvas);

		// addContentView(mWallpaperCanvasView, new ViewGroup.LayoutParams(
		// ViewGroup.LayoutParams.FILL_PARENT,
		// ViewGroup.LayoutParams.FILL_PARENT));

		// if (PROFILE_STARTUP) {
		// android.os.Debug.stopMethodTracing();
		// }

		if (!mRestoring) {
			// this.mAppShortcutZone.loadApplications();
			mModel.startLoader(this, true);
		}

		saveScreenInfo();
		// For handling default keys
		mDefaultKeySsb = new SpannableStringBuilder();
		Selection.setSelection(mDefaultKeySsb, 0);

		Log.i(TAG, "onCreate() ended");
	}

	/**
	 * 完整
	 */
	private void checkForLocaleChange() {
		final LocaleConfiguration localeConfiguration = new LocaleConfiguration();
		readConfiguration(this, localeConfiguration);

		final Configuration configuration = getResources().getConfiguration();
		final String previousLocale = localeConfiguration.locale;
		final String locale = configuration.locale.toString();

		final int previousMcc = localeConfiguration.mcc;
		final int mcc = configuration.mcc;

		final int previousMnc = localeConfiguration.mnc;
		final int mnc = configuration.mnc;

		mLocaleChanged = !locale.equals(previousLocale) || (mcc != previousMcc)
				|| (mnc != previousMnc);

		if (mLocaleChanged) {
			localeConfiguration.locale = locale;
			localeConfiguration.mcc = mcc;
			localeConfiguration.mnc = mnc;
			writeConfiguration(this, localeConfiguration);
			this.mIconCache.flush();
		}
	}

	private static void readConfiguration(Context context,
			LocaleConfiguration configuration) {
		DataInputStream in = null;

		try {
			in = new DataInputStream(context.openFileInput(PREFERENCES));
			configuration.locale = in.readUTF();
			configuration.mcc = in.readInt();
			configuration.mnc = in.readInt();
		} catch (FileNotFoundException e) {
			// Ignore
		} catch (IOException e) {
			// Ignore
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					// Ignore
				}
			}
		}
	}

	private static void writeConfiguration(Context context,
			LocaleConfiguration configuration) {
		DataOutputStream out = null;

		try {
			out = new DataOutputStream(context.openFileOutput(PREFERENCES,
					MODE_PRIVATE));
			out.writeUTF(configuration.locale);
			out.writeInt(configuration.mcc);
			out.writeInt(configuration.mnc);
			out.flush();
		} catch (FileNotFoundException e) {
			// Ignore
		} catch (IOException e) {
			// noinspection ResultOfMethodCallIgnored
			context.getFileStreamPath(PREFERENCES).delete();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					// Ignore
				}
			}
		}
	}

	void updateWindowTransparency() {
		if (!this.mForce16BitWindow) {
			return;
		} else {
			// WallpaperManager localWallpaperManager = (WallpaperManager)
			// getSystemService("wallpaper");
			//
			// if (localWallpaperManager.getWallpaperInfo() != null) {
			// setWindowTranslucent();
			// this.mWallpaperCanvasView.setVisibility(View.INVISIBLE);
			// this.mWallpaperImageDrawable = null;
			// } else {
			// setWindowOpaque();
			// this.mWallpaperCanvasView.setVisibility(View.VISIBLE);
			//
			// long l = SystemClock.uptimeMillis();
			// Drawable localDrawable = localWallpaperManager
			// .getFastDrawable();
			// this.mWallpaperImageDrawable = localDrawable;
			// makeBitmapMenuWallpaper();
			// }
		}
	}

	static int getScreen() {
		synchronized (sLock) {
			return sScreen;
		}
	}

	static void setScreen(int screen) {
		synchronized (sLock) {
			sScreen = screen;
		}
	}

	Drawable getCurrentImageMenuWallpaperDrawable() {
		return this.mDimWallpaperImageDrawable;
	}

	Drawable getCurrentImageWallpaperDrawable() {
		return this.mWallpaperImageDrawable;
	}

	private void setWallpaperDimension() {
		WallpaperManager wpm = (WallpaperManager) getSystemService(WALLPAPER_SERVICE);

		Display display = getWindowManager().getDefaultDisplay();
		boolean isPortrait = display.getWidth() < display.getHeight();

		final int width = isPortrait ? display.getWidth() : display.getHeight();
		final int height = isPortrait ? display.getHeight() : display
				.getWidth();
		wpm.suggestDesiredDimensions(width * WALLPAPER_SCREENS_SPAN, height);

		if ((mMenuWallpaperBitmap == null) && (this.mForce16BitWindow)) {
			int i1 = width * 2;
			Bitmap.Config localConfig = Bitmap.Config.RGB_565;
			mMenuWallpaperBitmap = Bitmap.createBitmap(i1, height, localConfig);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		LogUtils.d(TAG, "onActivityResult-requestCode=" + requestCode
				+ ", resultCode=" + resultCode);

		// Log.e(TAG,"onActivityResult");

		mWaitingForResult = false;

		// Log.e(TAG,"mWaitingForResult false   11111");

		// The pattern used here is that a user PICKs a specific application,
		// which, depending on the target, might need to CREATE the actual
		// target.

		// For example, the user would PICK_SHORTCUT for "Music playlist", and
		// we
		// launch over to the Music app to actually CREATE_SHORTCUT.

		// if (mAddItemCellInfo == null) {
		// Log.e(TAG, "mAddItemCellInfo == null");
		// }
		if ((resultCode == RESULT_OK) && (mAddItemCellInfo != null)) {
			// Log.e(TAG, "mAddItemCellInfo != null");
			switch (requestCode) {
			case REQUEST_PICK_APPLICATION:
				// completeAddApplication(this, data, mAddItemCellInfo,
				// !mDesktopLocked);
				completeAddApplication(this, data, mAddItemCellInfo);

				break;

			case REQUEST_PICK_SHORTCUT:
				processShortcut(data, REQUEST_PICK_APPLICATION,
						REQUEST_CREATE_SHORTCUT);

				break;

			case REQUEST_CREATE_SHORTCUT:
				completeAddShortcut(data, mAddItemCellInfo, !mDesktopLocked);

				break;

			case REQUEST_PICK_LIVE_FOLDER:
				addLiveFolder(data);

				break;

			case REQUEST_CREATE_LIVE_FOLDER:
				// completeAddLiveFolder(data, mAddItemCellInfo,
				// !mDesktopLocked);
				completeAddLiveFolder(data, mAddItemCellInfo);

				break;

			case REQUEST_PICK_APPWIDGET:
				addAppWidget(data);

				break;

			case REQUEST_CREATE_APPWIDGET:
				completeAddAppWidget(data, mAddItemCellInfo);

				break;
			}
		} else if (((requestCode == REQUEST_PICK_APPWIDGET) || (requestCode == REQUEST_CREATE_APPWIDGET))
				&& (resultCode == RESULT_CANCELED) && (data != null)) {
			// Clean up the appWidgetId if we canceled
			int appWidgetId = data.getIntExtra(
					AppWidgetManager.EXTRA_APPWIDGET_ID, -1);

			if (appWidgetId != -1) {
				mAppWidgetHost.deleteAppWidgetId(appWidgetId);
			}
		}
	}

	@Override
	protected void onResume() {
		// Log.e(TAG,"onResume");
		overridePendingTransitionForOpaqueWindowEnter();
		super.onResume();

		updateWindowTransparency();

		this.mIsActive = true;

		this.mExec = Executors.newSingleThreadExecutor();

		if (mRestoring) {
			this.mWorkspaceLoading = true;
			// this.mAppShortcutZone.loadApplications();
			mModel.startLoader(this, true);

			this.mRestoring = false;

			this.mDragLayer.cancelDrag();
			this.mMenuManager.resume();

			if (!this.mIsNewIntent) {
				this.mWorkspace.resume(sScreen);
			}

			// if (this.mQuickViewMainMenu.isOpened()) {
			// this.mQuickViewMainMenu.cancelDrag();
			// }

			if (this.mQuickViewWorkspace.isOpened()) {
				this.mQuickViewWorkspace.cancelDrag();
			}

			this.mIsNewIntent = false;
			this.mIsMoveDefaultScreen = false;

			if (!this.mIsScreenOff) {
				Handler localHandler3 = this.mHandler;
				Runnable r = new Runnable() {
					public void run() {
						updateWallpaperVisiblity();
					}
				};

				localHandler3.postDelayed(r, 1000L);
			}

			this.mIsScreenOff = false;
		}

		// If this was a new intent (i.e., the mIsNewIntent flag got set to true
		// by
		// onNewIntent), then close the search dialog if needed, because it
		// probably
		// came from the user pressing 'home' (rather than, for example,
		// pressing 'back').
		// if (mIsNewIntent) {
		// // Post to a handler so that this happens after the search dialog
		// // tries to open
		// // itself again.
		// mWorkspace.post(new Runnable() {
		// public void run() {
		// ISearchManager searchManagerService = ISearchManager.Stub
		// .asInterface(ServiceManager
		// .getService(Context.SEARCH_SERVICE));
		// try {
		// searchManagerService.stopSearch();
		// } catch (RemoteException e) {
		// e(LOG_TAG, "error stopping search", e);
		// }
		// }
		// });
		// }
		mIsNewIntent = false;
	}

	/**
	 * 完整
	 */
	void updateWallpaperVisiblity() {
		WallpaperManager localWallpaperManager = (WallpaperManager) getSystemService("wallpaper");

		if ((this.mMenuManager != null) && (this.mMenuManager.isOpened())) {
			SamsungUtils.setWallpaperVisibility(localWallpaperManager, false);
		} else {
			SamsungUtils.setWallpaperVisibility(localWallpaperManager, true);
		}
	}

	void overridePendingTransitionForOpaqueWindowEnter() {
		if (this.mIsOpaqueWindow) {
			overridePendingTransition(R.anim.wallpaper_open_enter,
					R.anim.wallpaper_open_exit);
		}
	}

	void overridePendingTransitionForOpaqueWindowExit() {
		if (this.mIsOpaqueWindow) {
			overridePendingTransition(R.anim.wallpaper_close_enter,
					R.anim.wallpaper_close_exit);
		}
	}

	/**
	 * 完整
	 */
	@Override
	protected void onPause() {
		super.onPause();
		closeDrawer(false);

		if (this.mExec != null) {
			this.mExec.shutdown();
			this.mExec = null;
		}

		this.mDragLayer.cancelDrag();
		saveScreenInfo();
		this.mIsActive = false;
		cancelAddWidget();
		this.mQuickViewWorkspace.cancelDrag();
		// this.mQuickViewMainMenu.cancelDrag();
		setWallpaperVisiblity(true);
	}

	/**
	 * 完整
	 */
	void cancelAddWidget() {
		int i = this.mAddWidgetType;

		if (i == ADDWIDGET_APPWIDGET) {
			if (this.mWidgetId != -1) {
				this.mAppWidgetHost.deleteAppWidgetId(this.mWidgetId);
			}

			this.mWidgetId = -1;
			this.mAppWidgetInfo = null;
			this.mLauncherAppWidgetInfo = null;
		}

		this.mWidgetPreview.removeAllViews();
		this.mWidgetPreview.setVisibility(View.INVISIBLE);
		this.mWorkspace.stopAutoScrollRunnable();

		if (this.mToast != null) {
			this.mToast.cancel();
		}

		clearAddWidget();
	}

	/**
	 * 完整
	 */
	void clearAddWidget() {
		this.mAddWidgetType = 0;
		this.mWidgetId = -1;
		this.mBlankScreen[0] = -1;
		this.mBlankScreen[1] = -1;
		this.mMenuManager.unlock();
	}

	/**
	 * 完整
	 * 
	 * @param visiblity
	 */
	void setWallpaperVisiblity(boolean visiblity) {
		SamsungUtils.setWallpaperVisibility(
				(WallpaperManager) getSystemService(WALLPAPER_SERVICE),
				visiblity);
	}

	/**
	 * 完整
	 */
	@Override
	public Object onRetainNonConfigurationInstance() {
		mModel.stopLoader();

		return Boolean.TRUE;
	}

	/**
	 * 完整
	 * 
	 * @return
	 */
	private boolean acceptFilter() {
		final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

		return !inputManager.isFullscreenMode();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		boolean handled = super.onKeyDown(keyCode, event);

		if (!handled && acceptFilter() && (keyCode != KeyEvent.KEYCODE_ENTER)) {
			boolean gotKey = TextKeyListener.getInstance().onKeyDown(
					mWorkspace, mDefaultKeySsb, keyCode, event);

			if (gotKey && (mDefaultKeySsb != null)
					&& (mDefaultKeySsb.length() > 0)) {
				// something usable has been typed - start a search
				// the typed text will be retrieved and cleared by
				// showSearchDialog()
				// If there are multiple keystrokes before the search dialog
				// takes focus,
				// onSearchRequested() will be called for every keystroke,
				// but it is idempotent, so it's fine.
				return onSearchRequested();
			}
		}

		return handled;
	}

	private String getTypedText() {
		return mDefaultKeySsb.toString();
	}

	private void clearTypedText() {
		mDefaultKeySsb.clear();
		mDefaultKeySsb.clearSpans();
		Selection.setSelection(mDefaultKeySsb, 0);
	}

	/**
	 * Restores the previous state, if it exists.
	 * 
	 * @param savedState
	 *            The previous state.
	 */
	private void restoreState(Bundle savedState) {
		// Log.e(TAG,"restoreState "+savedState );

		if (savedState == null) {
			return;
		}

		mUninstallPackageName = savedState
				.getString(RUNTIME_STATE_DELETE_APPLICATION);

		final int currentScreen = savedState.getInt(
				RUNTIME_STATE_CURRENT_SCREEN, -1);

		// Log.e(TAG,"currentScreen "+currentScreen);

		if (currentScreen > -1) {
			mWorkspace.setCurrentScreen(currentScreen);
		}

		int j = savedState.getInt(RUNTIME_STATE_MENU_CURRENT_MODE, 0);

		if (j == 1) {
			this.mMenuManager.setMode(1);
		}

		// Log.e(TAG,"RUNTIME_STATE_MENU_CURRENT_MODE "+ j );

		int k = savedState.getInt(RUNTIME_STATE_MENU_CURRENT_SCREEN, -1);

		if (k > -1) {
			this.mMenuManager.setCurrentScreen(k);
		}

		final int addScreen = savedState.getInt(
				RUNTIME_STATE_PENDING_ADD_SCREEN, -1);

		if (addScreen > -1) {
			this.mAddItemCellInfo = new CellLayout.CellInfo();

			final CellLayout.CellInfo addItemCellInfo = this.mAddItemCellInfo;
			addItemCellInfo.valid = true;
			addItemCellInfo.screen = addScreen;
			addItemCellInfo.cellX = savedState
					.getInt(RUNTIME_STATE_PENDING_ADD_CELL_X);
			addItemCellInfo.cellY = savedState
					.getInt(RUNTIME_STATE_PENDING_ADD_CELL_Y);
			addItemCellInfo.spanX = savedState
					.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_X);
			addItemCellInfo.spanY = savedState
					.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y);
			addItemCellInfo.findVacantCellsFromOccupied(savedState
					.getBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS),
					savedState.getInt(RUNTIME_STATE_PENDING_ADD_COUNT_X),
					savedState.getInt(RUNTIME_STATE_PENDING_ADD_COUNT_Y));
			mRestoring = true;
		}

		boolean renameFolder = savedState.getBoolean(
				RUNTIME_STATE_PENDING_FOLDER_RENAME, false);

		if (renameFolder) {
			long id = savedState
					.getLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID);
			mFolderInfo = mModel.getFolderById(this, mFolders, id);
			mRestoring = true;
		}

		if (savedState.getBoolean("launcher.all_apps_folder", false)) {
			this.mMenuManager.open();
		}

		this.mStateQuickNavigation = savedState.getInt(
				RUNTIME_STATE_QUICK_NAVIGATION, -1);

		if (this.mStateQuickNavigation == 1) {
			if (!this.mMainMenuLoading) {
				Log.d("Launcher",
						"MainMenu loading is already finished. opening QuickViewMainMenu in restoreState()");
				// openQuickViewMainMenu();
				this.mStateQuickNavigation = -1;
			}
		} else {
			this.mMenuScreenCount = savedState.getInt(
					RUNTIME_STATE_MENU_SCREEN_COUNT, -1);

			this.mDeleteIndex = savedState.getInt(
					RUNTIME_STATE_DELETE_WORKSCREEN_INDEX, -1);

			if (this.mDeleteIndex >= 0) {
				this.mIsDeletePopup = true;
			}

			if (this.mStateQuickNavigation == 0) {
				Log.d("Launcher",
						"opening QuickViewWorkspace in restoreState()");
				openQuickViewWorkspace();
				this.mStateQuickNavigation = -1;
			}
		}
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		// NOTE: Do NOT do this. Ever. This is a terrible and horrifying hack.
		//
		// Home loads the content of the workspace on a background thread. This
		// means that
		// a previously focused view will be, after orientation change, added to
		// the view
		// hierarchy at an undeterminate time in the future. If we were to
		// invoke
		// super.onRestoreInstanceState() here, the focus restoration would fail
		// because the
		// view to focus does not exist yet.
		//
		// However, not invoking super.onRestoreInstanceState() is equally bad.
		// In such a case,
		// panels would not be restored properly. For instance, if the menu is
		// open then the
		// user changes the orientation, the menu would not be opened in the new
		// orientation.
		//
		// To solve both issues Home messes up with the internal state of the
		// bundle to remove
		// the properties it does not want to see restored at this moment. After
		// invoking
		// super.onRestoreInstanceState(), it removes the panels state.
		//
		// Later, when the workspace is done loading, Home calls
		// super.onRestoreInstanceState()
		// again to restore focus and other view properties. It will not,
		// however, restore
		// the panels since at this point the panels' state has been removed
		// from the bundle.
		//
		// This is a bad example, do not do this.
		//
		// If you are curious on how this code was put together, take a look at
		// the following
		// in Android's source code:
		// - Activity.onRestoreInstanceState()
		// - PhoneWindow.restoreHierarchyState()
		// - PhoneWindow.DecorView.onAttachedToWindow()
		//
		// The source code of these various methods shows what states should be
		// kept to
		// achieve what we want here.

		Bundle windowState = savedInstanceState
				.getBundle("android:viewHierarchyState");
		SparseArray<Parcelable> savedStates = null;
		int focusedViewId = View.NO_ID;

		if (windowState != null) {
			savedStates = windowState.getSparseParcelableArray("android:views");
			windowState.remove("android:views");
			focusedViewId = windowState.getInt("android:focusedViewId",
					View.NO_ID);
			windowState.remove("android:focusedViewId");
		}

		super.onRestoreInstanceState(savedInstanceState);

		if (windowState != null) {
			windowState.putSparseParcelableArray("android:views", savedStates);
			windowState.putInt("android:focusedViewId", focusedViewId);
			windowState.remove("android:Panels");
		}

		mSavedInstanceState = savedInstanceState;
	}

	/**
	 * Finds all the views we need and configure them properly.
	 */
	private void setupViews() {
		mDragLayer = (DragLayer) findViewById(R.id.drag_layer);

		final DragLayer dragLayer = mDragLayer;

		mWorkspace = (Workspace) dragLayer.findViewById(R.id.workspace);

		SharedPreferences localSharedPreferences = this.mPrefs;
		int j = DEFAULT_SCREEN_COUNT;
		int k = localSharedPreferences.getInt(PREFERENCES_SCREENCOUNT, j);
		int m = 0;

		while (m < k) {
			CellLayout localCellLayout = (CellLayout) LayoutInflater.from(this)
					.inflate(R.layout.workspace_screen, mWorkspace, false);
			int n = getCellLayoutId(m);
			localCellLayout.setId(n);

			ViewGroup.LayoutParams localLayoutParams = localCellLayout
					.getLayoutParams();

			if (localLayoutParams == null) {
				localLayoutParams = new ViewGroup.LayoutParams(-1, -1);
			}

			mWorkspace.addView(localCellLayout, localLayoutParams);
			m++;
		}

		int i1 = this.mPrefs.getInt(PREFERENCES_CURRENTSCREEN, DEFAULT_SCREN);
		// Log.e(TAG,"PREFERENCES_CURRENTSCREEN "+i1);

		if (i1 >= k) {
			i1 = 0;
		}
		// Log.e(TAG,"PREFERENCES_CURRENTSCREEN "+i1);
		sScreen = i1;
		final Workspace workspace = mWorkspace;
		workspace.setCurrentScreen(i1);
		workspace.setOnLongClickListener(this);
		workspace.setDragger(dragLayer);
		workspace.setLauncher(this);

		dragLayer.setDragScoller(workspace);

		AppShortcutZone localAppShortcutZone2 = (AppShortcutZone) dragLayer
				.findViewById(R.id.shortcut_zone);
		localAppShortcutZone2.setLauncher(this);
		localAppShortcutZone2.setDragger(dragLayer);
		this.mAppShortcutZone = localAppShortcutZone2;

		mMenuDrawer = (MenuDrawer) dragLayer.findViewById(R.id.menudrawer);
		dragLayer.setIgnoredDropTarget(mMenuDrawer);

		mMenuManager = (MenuManager) dragLayer.findViewById(R.id.menumanager);
		mMenuManager.setLauncher(this);
		mMenuManager.setDragger(dragLayer);
		mMenuManager.setMode(loadMenuMode());

		this.mDeleteZone = (DeleteZone) dragLayer
				.findViewById(R.id.delete_zone);
		this.mDeleteZone.setLauncher(this);
		this.mDeleteZone.setDragController(dragLayer);
		mDeleteZone.setHandle(mAppShortcutZone);

		dragLayer.setDragListener(mDeleteZone);
		dragLayer.setDragMenuScoller(mMenuManager);

		this.mQuickViewWorkspace = (QuickViewWorkspace) dragLayer
				.findViewById(R.id.quickviewworkspace);

		this.mQuickViewWorkspace.setLauncher(this);

		// this.mQuickViewMainMenu = (QuickViewMainMenu) dragLayer
		// .findViewById(R.id.quickviewmainmenu);
		// this.mQuickViewMainMenu.setLauncher(this);

		this.mWidgetPreview = (WidgetPreview) dragLayer
				.findViewById(R.id.widget_preview);

		SharedPreferences sh = PreferenceManager
				.getDefaultSharedPreferences(this);

		int type = Integer.parseInt(sh.getString(
				PreferenceWithDesktopSetting.KEY_DESKTOP, "0"));

		// Log.e(TAG, "" + type);

		Workspace.setAninmationType(type);

		type = Integer.parseInt(sh.getString(
				PreferenceWithDesktopSetting.KEY_FUC_OUT_MENU, "0"));

		// Log.e(TAG, "" + type);
		MenuManager.setAninmationType(type);

		type = Integer.parseInt(sh.getString(
				PreferenceWithDesktopSetting.KEY_FUC_ICON_MENU, "0"));

		// Log.e(TAG, "" + type);
		AppMenu.setAninmationType(type);
	}

	AppShortcutZone getAppShortcutZone() {
		return this.mAppShortcutZone;
	}

	/**
	 * 完整
	 */
	public void saveScreenInfo() {
		SharedPreferences.Editor localEditor1 = this.mPrefs.edit();
		localEditor1.putInt(PREFERENCES_SCREENCOUNT,
				this.mWorkspace.getChildCount());
		// Log.e(TAG,"saveScreenInfo "+sScreen);
		localEditor1.putInt(PREFERENCES_CURRENTSCREEN, sScreen);
		localEditor1.commit();
	}

	/**
	 * 完整
	 */
	void lockAllApps() {
		this.mMenuManager.lock();
	}

	MenuDrawer getMenuDrawer() {
		return this.mMenuDrawer;
	}

	MenuManager getMenuManager() {
		return this.mMenuManager;
	}

	/**
	 * Creates a view representing a shortcut.
	 */
	View createShortcut(int paramInt, ViewGroup viewGroup,
			ShortcutInfo shortcutInfo) {
		TextView localTextView = (TextView) this.mInflater.inflate(paramInt,
				viewGroup, false);
		Bitmap localBitmap = shortcutInfo.getIcon(this.mIconCache);
		FastBitmapDrawable localFastBitmapDrawable = new FastBitmapDrawable(
				localBitmap);
		localTextView.setCompoundDrawablesWithIntrinsicBounds(null,
				localFastBitmapDrawable, null, null);

		CharSequence localCharSequence = shortcutInfo.title;
		localTextView.setText(localCharSequence);
		localTextView.setTag(shortcutInfo);
		localTextView.setOnClickListener(this);

		return localTextView;
	}

	/**
	 * Add an application shortcut to the workspace.
	 */
	void completeAddApplication(Context context, Intent data,
			CellLayout.CellInfo cellInfo) {
		cellInfo.screen = mWorkspace.getCurrentScreen();

		if (!findSingleSlot(cellInfo)) {
			return;
		}

		// LauncherModel localLauncherModel = this.mModel;
		PackageManager localPackageManager = context.getPackageManager();
		ShortcutInfo localShortcutInfo = mModel.getShortcutInfo(
				localPackageManager, data, context);

		if (localShortcutInfo != null) {
			ComponentName localComponentName = data.getComponent();
			localShortcutInfo.setActivity(localComponentName,
					Intent.FLAG_ACTIVITY_NEW_TASK
							| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
			localShortcutInfo.container = ItemInfo.NO_ID;

			boolean bool = isWorkspaceLocked();
			this.mWorkspace.addApplicationShortcut(localShortcutInfo, cellInfo,
					bool);
		} else {
			String str = "Couldn't find ActivityInfo for selected application: "
					+ data;
			Log.e("Launcher", str);
		}
	}

	private static ApplicationInfo infoFromApplicationIntent(Context context,
			Intent data) {
		ComponentName component = data.getComponent();
		PackageManager packageManager = context.getPackageManager();
		ActivityInfo activityInfo = null;

		try {
			activityInfo = packageManager.getActivityInfo(component, 0 /*
																		 * no
																		 * flags
																		 */);
		} catch (NameNotFoundException e) {
			e(TAG, "Couldn't find ActivityInfo for selected application", e);
		}

		if (activityInfo != null) {
			ApplicationInfo itemInfo = new ApplicationInfo();

			itemInfo.title = activityInfo.loadLabel(packageManager);

			if (itemInfo.title == null) {
				itemInfo.title = activityInfo.name;
			}

			itemInfo.setActivity(component, Intent.FLAG_ACTIVITY_NEW_TASK
					| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
			itemInfo.icon = activityInfo.loadIcon(packageManager);
			itemInfo.container = ItemInfo.NO_ID;

			return itemInfo;
		}

		return null;
	}

	/**
	 * Add a shortcut to the workspace.
	 */
	private void completeAddShortcut(Intent data, CellLayout.CellInfo cellInfo,
			boolean insertAtFirst) {
		Log.e(TAG, "completeAddShortcut");

		cellInfo.screen = mWorkspace.getCurrentScreen();

		if (!findSingleSlot(cellInfo)) {
			return;
		}

		ShortcutInfo localShortcutInfo = mModel.addShortcut(this, data,
				cellInfo, false);

		if (!this.mRestoring) {
			boolean bool = isWorkspaceLocked();
			this.mWorkspace.addApplicationShortcut(localShortcutInfo, cellInfo,
					bool);
		}
	}

	private void completeAddAppWidget(Intent data, CellLayout.CellInfo cellInfo) {
		Bundle extras = data.getExtras();
		int appWidgetId = extras
				.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);

		if (LOGD) {
			d(TAG, "dumping extras content=" + extras.toString());
		}

		AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager
				.getAppWidgetInfo(appWidgetId);

		// Calculate the grid spans needed to fit this widget
		CellLayout layout = (CellLayout) mWorkspace.getChildAt(cellInfo.screen);
		int[] spans = layout.rectToCell(appWidgetInfo.minWidth,
				appWidgetInfo.minHeight);

		// Try finding open space on Launcher screen
		final int[] xy = mCellCoordinates;

		if (!findSlot(cellInfo, xy, spans[0], spans[1])) {
			if (appWidgetId != -1) {
				mAppWidgetHost.deleteAppWidgetId(appWidgetId);
			}

			return;
		}

		// Build Launcher-specific widget info and save to database
		LauncherAppWidgetInfo launcherInfo = new LauncherAppWidgetInfo(
				appWidgetId);
		launcherInfo.spanX = spans[0];
		launcherInfo.spanY = spans[1];

		LauncherModel.addItemToDatabase(this, launcherInfo,
				LauncherSettings.Favorites.CONTAINER_DESKTOP,
				mWorkspace.getCurrentScreen(), xy[0], xy[1], false);

		if (!mRestoring) {
			// sModel.addDesktopAppWidget(launcherInfo);
			this.mDesktopItems.add(launcherInfo);
			// Perform actual inflation because we're live
			launcherInfo.hostView = mAppWidgetHost.createView(this,
					appWidgetId, appWidgetInfo);

			launcherInfo.hostView.setAppWidget(appWidgetId, appWidgetInfo);
			launcherInfo.hostView.setTag(launcherInfo);

			boolean desktopLocked = isWorkspaceLocked();

			mWorkspace.addInCurrentScreen(launcherInfo.hostView, xy[0], xy[1],
					launcherInfo.spanX, launcherInfo.spanY, desktopLocked);
		}

		// else if (sModel.isDesktopLoaded()) {
		// sModel.addDesktopAppWidget(launcherInfo);
		// }
	}

	public LauncherAppWidgetHost getAppWidgetHost() {
		return mAppWidgetHost;
	}

	/**
	 * 完整
	 * 
	 * @param info
	 */
	public void addShortcut(ItemInfo info) {
		this.mDesktopItems.add(info);
	}

	static ApplicationInfo addShortcut(Context context, Intent data,
			CellLayout.CellInfo cellInfo, boolean notify) {
		final ApplicationInfo info = infoFromShortcutIntent(context, data);
		LauncherModel.addItemToDatabase(context, info,
				LauncherSettings.Favorites.CONTAINER_DESKTOP, cellInfo.screen,
				cellInfo.cellX, cellInfo.cellY, notify);

		return info;
	}

	private static ApplicationInfo infoFromShortcutIntent(Context context,
			Intent data) {
		Log.e(TAG, "infoFromShortcutIntent");

		Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
		String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
		Bitmap bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);

		Drawable icon = null;
		boolean filtered = false;
		boolean customIcon = false;
		ShortcutIconResource iconResource = null;

		if (bitmap != null) {
			icon = new FastBitmapDrawable(Utilities.createBitmapThumbnail(
					bitmap, context, null));
			filtered = true;
			customIcon = true;
		} else {
			Parcelable extra = data
					.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);

			if ((extra != null) && extra instanceof ShortcutIconResource) {
				try {
					iconResource = (ShortcutIconResource) extra;

					final PackageManager packageManager = context
							.getPackageManager();
					Resources resources = packageManager
							.getResourcesForApplication(iconResource.packageName);
					final int id = resources.getIdentifier(
							iconResource.resourceName, null, null);
					icon = resources.getDrawable(id);
				} catch (Exception e) {
					w(TAG, "Could not load shortcut icon: " + extra);
				}
			}
		}

		if (icon == null) {
			icon = context.getPackageManager().getDefaultActivityIcon();
		}

		final ApplicationInfo info = new ApplicationInfo();
		info.icon = icon;
		info.filtered = filtered;
		info.title = name;
		info.intent = intent;
		info.customIcon = customIcon;
		info.iconResource = iconResource;

		return info;
	}

	/**
	 * 完整
	 */
	void closeSystemDialogs() {
		getWindow().closeAllPanels();

		try {
			dismissDialog(DIALOG_CREATE_SHORTCUT);
			// Unlock the workspace if the dialog was showing
			mWorkspace.unlock();
		} catch (Exception e) {
			// An exception is thrown if the dialog is not visible, which is
			// fine
		}

		try {
			dismissDialog(DIALOG_RENAME_FOLDER);
			// Unlock the workspace if the dialog was showing
			mWorkspace.unlock();
		} catch (Exception e) {
			// An exception is thrown if the dialog is not visible, which is
			// fine
		}

		try {
			mUninstallPackageName = null;
			dismissDialog(DIALOG_DELETE_APPLICATION);
		} catch (Exception e) {
			// An exception is thrown if the dialog is not visible, which is
			// fine
		}

		try {
			dismissDialog(DIALOG_DISCARD_MENUEDIT);
		} catch (Exception e) {
			// An exception is thrown if the dialog is not visible, which is
			// fine
		}

		try {
			dismissDialog(DIALOG_DELETE_WORKSCREEN);
		} catch (Exception e) {
			// An exception is thrown if the dialog is not visible, which is
			// fine
		}

		mWaitingForResult = false;

		// Log.e(TAG,"mWaitingForResult false   2222");
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		Log.e(TAG, "onNewIntent");

		// Close the menu
		if (Intent.ACTION_MAIN.equals(intent.getAction())) {
			closeSystemDialogs();

			// Set this flag so that onResume knows to close the search dialog
			// if it's open,
			// because this was a new intent (thus a press of 'home' or some
			// such) rather than
			// for example onResume being called when the user pressed the
			// 'back' button.
			mIsNewIntent = true;

			if ((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) {
				if (!mWorkspace.isDefaultScreenShowing()) {
					mWorkspace.moveToDefaultScreen();
				}

				closeDrawer();

				if (this.mQuickViewWorkspace.isOpened()) {
					closeQuickViewWorkspace();
				}

				// if (this.mQuickViewMainMenu.isOpened()) {
				// closeQuickViewMainMenu();
				// }

				this.mStateQuickNavigation = -1;

				final View v = getWindow().peekDecorView();

				if ((v != null) && (v.getWindowToken() != null)) {
					InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
				}
			} else {
				closeDrawer(false);
			}
		}
	}

	/**
	 * 完整
	 */
	void openQuickViewWorkspace() {
		Log.e(TAG, "openQuickViewWorkspace start");
		this.mAppShortcutZone.setVisibility(View.GONE);
		this.mWorkspace.setVisibility(View.INVISIBLE);
		// this.mWorkspace.invalidate();
		mQuickViewWorkspace.initScreen(this.mWorkspace.getChildCount());
		// closeOptionsMenu();
		this.mQuickViewWorkspace.open();
		Log.e(TAG, "openQuickViewWorkspace end");
	}

	void closeQuickViewWorkspace() {

		Log.e(TAG, "closeQuickViewWorkspace start   ");

		if (!this.mQuickViewWorkspace.isOpened()) {
			return;
		}

		// Log.e(TAG, "closeQuickViewWorkspace start  1 ");
		// getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		this.mQuickViewWorkspace.close();
		this.mAppShortcutZone.setVisibility(View.VISIBLE);
		int i = this.mQuickViewWorkspace.getCurrentPage();
		setScreen(i);
		this.mWorkspace.updateWallpaperOffset();
		this.mWorkspace.setVisibility(View.VISIBLE);
		this.mAppShortcutZone.setVisibility(View.VISIBLE);

		Workspace localWorkspace = this.mWorkspace;
		int k = this.mWorkspace.getCurrentScreen();
		// Log.e(TAG, "getCurrentScreen " + k);
		localWorkspace.getChildAt(k).requestFocus();
		this.mWorkspace.setCurrentScreen(i);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {

		super.onSaveInstanceState(outState);

		// Log.e(TAG,"onSaveInstanceState");

		outState.putInt(RUNTIME_STATE_CURRENT_SCREEN,
				this.mWorkspace.getCurrentScreen());

		// Log.e(TAG,"getCurrentScreen "+this.mWorkspace.getCurrentScreen());

		outState.putString(RUNTIME_STATE_DELETE_APPLICATION,
				mUninstallPackageName);

		int k = this.mMenuManager.getMode();

		if (k == 1) {
			outState.putInt(RUNTIME_STATE_MENU_CURRENT_MODE, k);
		}

		// Log.e(TAG,"onSaveInstanceState RUNTIME_STATE_MENU_CURRENT_MODE "+k);

		int j = this.mMenuManager.getCurrentScreen();

		outState.putInt(RUNTIME_STATE_MENU_CURRENT_SCREEN, j);

		int m = this.mMenuManager.getChildCount();

		outState.putInt(RUNTIME_STATE_MENU_SCREEN_COUNT, m);

		if (this.mStateQuickNavigation > -1) {
			int n = this.mStateQuickNavigation;
			outState.putInt(RUNTIME_STATE_QUICK_NAVIGATION, n);

			if (this.mDeleteIndex > -1) {
				int i1 = this.mDeleteIndex;
				outState.putInt(RUNTIME_STATE_DELETE_WORKSCREEN_INDEX, i1);
			}
		} else {
			if (this.mQuickViewWorkspace.isOpened()) {
				outState.putInt(RUNTIME_STATE_QUICK_NAVIGATION, 0);

				if (this.mIsDeletePopup) {
					int i5 = this.mQuickViewWorkspace.getDeleteIndex();
					outState.putInt(RUNTIME_STATE_DELETE_WORKSCREEN_INDEX, i5);
				} else {
					outState.putInt(RUNTIME_STATE_DELETE_WORKSCREEN_INDEX, -1);
				}
			} else {
				// if (this.mQuickViewMainMenu.isOpened()) {
				// outState.putInt(RUNTIME_STATE_QUICK_NAVIGATION, 1);
				// } else {
				// outState.putInt(RUNTIME_STATE_QUICK_NAVIGATION, -1);
				// }
			}
		}

		if (this.mMenuManager.isOpened()) {
			outState.putBoolean("launcher.all_apps_folder", true);
		}

		final ArrayList<Folder> folders = mWorkspace.getOpenFolders();

		if (folders.size() > 0) {
			final int count = folders.size();
			long[] ids = new long[count];

			for (int i = 0; i < count; i++) {
				final FolderInfo info = folders.get(i).getInfo();
				ids[i] = info.id;
			}

			outState.putLongArray(RUNTIME_STATE_USER_FOLDERS, ids);
		}

		// final boolean isConfigurationChange = getChangingConfigurations() !=
		// 0;

		// When the drawer is opened and we are saving the state because of a
		// configuration change
		// if (mDrawer.isOpened() && isConfigurationChange) {
		// outState.putBoolean(RUNTIME_STATE_ALL_APPS_FOLDER, true);
		// }
		if ((this.mAddItemCellInfo != null) && mAddItemCellInfo.valid
				&& mWaitingForResult) {
			final CellLayout.CellInfo addItemCellInfo = this.mAddItemCellInfo;
			final CellLayout layout = (CellLayout) mWorkspace
					.getChildAt(addItemCellInfo.screen);

			outState.putInt(RUNTIME_STATE_PENDING_ADD_SCREEN,
					addItemCellInfo.screen);
			outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_X,
					addItemCellInfo.cellX);
			outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_Y,
					addItemCellInfo.cellY);
			outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_X,
					addItemCellInfo.spanX);
			outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y,
					addItemCellInfo.spanY);
			outState.putInt(RUNTIME_STATE_PENDING_ADD_COUNT_X,
					layout.getCountX());
			outState.putInt(RUNTIME_STATE_PENDING_ADD_COUNT_Y,
					layout.getCountY());
			outState.putBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS,
					layout.getOccupiedCells());
		}

		if ((mFolderInfo != null) && mWaitingForResult) {
			outState.putBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, true);
			outState.putLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID,
					mFolderInfo.id);
		}

		if (this.mDeleteIndex > -1) {
			outState.putInt(RUNTIME_STATE_DELETE_WORKSCREEN_INDEX,
					this.mDeleteIndex);
		}

		// Iterator<String> it = outState.keySet().iterator();
		//
		// while(it.hasNext())
		// {
		// Log.e(TAG,"  "+ it.next());
		// }

	}

	/**
	 * 完整
	 */
	public void onWindowFocusChanged(boolean hasFocus) {
		super.onWindowFocusChanged(hasFocus);
		setWallpaperDimension();
		this.mWorkspace.updateWallpaperOffset();

		if (hasFocus) {
			updateWindowTransparency();
			return;
		}

		this.mQuickViewWorkspace.cancelDrag();
		// this.mQuickViewMainMenu.cancelDrag();
	}

	/**
	 * 完整
	 */
	public void onDestroy() {
		Log.e(TAG, "onDestroy");
		this.mDestroyed = true;
		super.onDestroy();
		cancelAddWidget();
		this.removeDialog(DIALOG_CREATE_SHORTCUT);
		this.removeDialog(DIALOG_RENAME_FOLDER);
		this.removeDialog(DIALOG_DELETE_APPLICATION);
		this.removeDialog(DIALOG_DISCARD_MENUEDIT);
		this.removeDialog(DIALOG_DELETE_WORKSCREEN);
		this.optionMenu = null;
		try {
			this.mAppWidgetHost.stopListening();
			TextKeyListener.getInstance().release();
			this.mModel.stopLoader();
			unbindDesktopItems();
			this.mMenuManager.setAdapter(null);
			getContentResolver()
					.unregisterContentObserver(this.mWidgetObserver);
			unregisterReceiver(this.mCloseSystemDialogsReceiver);
			unregisterReceiver(this.mWallpaperChangedReceiver);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void startActivityForResult(Intent intent, int requestCode) {
		if (requestCode >= 0) {
			mWaitingForResult = true;
			// Log.e(TAG,"mWaitingForResult true   3333");
		}
		super.startActivityForResult(intent, requestCode);
	}

	@Override
	public void startSearch(String initialQuery, boolean selectInitialQuery,
			Bundle appSearchData, boolean globalSearch) {
		closeDrawer(false);

		// Slide the search widget to the top, if it's on the current screen,
		// otherwise show the search dialog immediately.
		Search searchWidget = mWorkspace.findSearchWidgetOnCurrentScreen();

		if (searchWidget == null) {
			showSearchDialog(initialQuery, selectInitialQuery, appSearchData,
					globalSearch);
		} else {
			searchWidget.startSearch(initialQuery, selectInitialQuery,
					appSearchData, globalSearch);
			// show the currently typed text in the search widget while sliding
			searchWidget.setQuery(getTypedText());
		}
	}

	/**
	 * Show the search dialog immediately, without changing the search widget.
	 * 
	 * @see Activity#startSearch(String, boolean, android.os.Bundle, boolean)
	 */
	void showSearchDialog(String initialQuery, boolean selectInitialQuery,
			Bundle appSearchData, boolean globalSearch) {
		if (initialQuery == null) {
			// Use any text typed in the launcher as the initial query
			initialQuery = getTypedText();
			clearTypedText();
		}

		if (appSearchData == null) {
			appSearchData = new Bundle();
			// appSearchData.putString(SearchManager.SOURCE, "launcher-search");
		}

		final SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);

		final Search searchWidget = mWorkspace
				.findSearchWidgetOnCurrentScreen();

		if (searchWidget != null) {
			// This gets called when the user leaves the search dialog to go
			// back to
			// the Launcher.
			searchManager
					.setOnCancelListener(new SearchManager.OnCancelListener() {
						public void onCancel() {
							searchManager.setOnCancelListener(null);
							stopSearch();
						}
					});
		}

		searchManager.startSearch(initialQuery, selectInitialQuery,
				getComponentName(), appSearchData, globalSearch);
	}

	/**
	 * Cancel search dialog if it is open.
	 */
	void stopSearch() {
		// Close search dialog
		SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
		searchManager.stopSearch();

		// Restore search widget to its normal position
		Search searchWidget = mWorkspace.findSearchWidgetOnCurrentScreen();

		if (searchWidget != null) {
			searchWidget.stopSearch(false);
		}
	}

	/**
	 * 底部菜单
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		optionMenu = new OptionMenu(this);

		optionMenu.add(MENU_GROUP_ADD, MENU_ADD, 0, R.string.menu_add)
				.setIcon(R.drawable.ic_menu_add).setAlphabeticShortcut('A');
		optionMenu
				.add(MENU_GROUP_DEFAULT, MENU_WALLPAPER_SETTINGS, 0,
						R.string.menu_wallpaper)
				.setIcon(R.drawable.ic_menu_wallpaper)
				.setAlphabeticShortcut('W');

		// 系统设置
		final Intent settings = new Intent(
				android.provider.Settings.ACTION_SETTINGS);
		settings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
				| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);

		optionMenu
				.add(MENU_GROUP_DEFAULT, MENU_SETTINGS, 0,
						R.string.menu_settings)
				.setIcon(R.drawable.ic_menu_settings)
				.setAlphabeticShortcut('P').setIntent(settings);

		// 桌面设置
		optionMenu
				.add(MENU_GROUP_DEFAULT, MENU_DESKTOP_SET, 0,
						R.string.desktopSetting)
				.setIcon(R.drawable.ic_menu_edit).setAlphabeticShortcut('D');

		optionMenu
				.add(MENU_GROUP_DEFAULT, MENU_QUICKVIEW_WORKSPACE, 0,
						R.string.menu_edit).setIcon(R.drawable.ic_menu_edit)
				.setAlphabeticShortcut('D');

		// 通知
		// optionMenu.add(MENU_GROUP_DEFAULT, MENU_NOTIFICATIONS, 0,
		// R.string.menu_notifications)
		// .setIcon(R.drawable.ic_menu_details).setAlphabeticShortcut('N');

		optionMenu.add(MENU_GROUP_DEFAULT_MENU, MENU_MENUEDIT, 0,
				R.string.menu_edit).setIcon(R.drawable.ic_menu_edit);

		// 搜索
		// optionMenu.add(MENU_GROUP_DEFAULT, MENU_SEARCH, 0,
		// R.string.menu_search)
		// .setIcon(R.drawable.ic_menu_search).setAlphabeticShortcut(SearchManager.MENU_KEY);

		// 为了菜单的美观,添加一个"联系人"菜单项
		Intent contacts = new Intent();
		ComponentName comp = new ComponentName("com.android.contacts",
				"com.android.contacts.DialtactsContactsEntryActivity");
		contacts.setComponent(comp);
		contacts.setAction("android.intent.action.MAIN");
		// contacts.setAction(Intent.ACTION_GET_CONTENT);
		// contacts.setType("vnd.android.cursor.item/phone");

		// optionMenu.add(MENU_GROUP_DEFAULT, MENU_CONTACTS, 0,
		// R.string.menu_contacts)
		// .setIcon(R.drawable.contact).setIntent(contacts);

		if (USE_MAINMENU_LISTMODE) {
			optionMenu.add(MENU_GROUP_DEFAULT_MENU, MENU_LISTVIEW, 0,
					R.string.menu_listview).setIcon(
					R.drawable.ic_menu_list_view);
		}

		optionMenu.add(MENU_GROUP_LIST_MENU, MENU_GRIDVIEW, 0,
				R.string.menu_gridview).setIcon(R.drawable.ic_menu_grid_view);

		optionMenu.add(MENU_GROUP_EDIT_MENU, MENU_SAVE, 0, R.string.menu_save)
				.setIcon(R.drawable.ic_menu_save);

		optionMenu.add(MENU_GROUP_EDIT_MENU, MENU_DISCARD, 0,
				R.string.menu_discard).setIcon(R.drawable.ic_menu_cancel);

		// 必须加上下面这行.
		menu.add("");
		return true;
	}

	@Override
	public boolean onMenuOpened(int featureId, Menu menu) {
		optionMenu.onMenuOpened(mDragLayer);
		return false;
	}

	@Override
	protected void onStop() {
		super.onStop();
		if (null != optionMenu) {
			optionMenu.close();
		}
	}

	public boolean onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);
		this.mMenuAddInfo = this.mWorkspace.findAllVacantCells(null);

		if (this.mQuickViewWorkspace.isOpened()) {
			return false;
		}

		if (this.mMenuManager.isOpened()) {
			optionMenu.setGroupVisible(MENU_GROUP_DEFAULT, false);
			optionMenu.setGroupVisible(MENU_GROUP_ADD, false);
			optionMenu.setGroupVisible(MENU_GROUP_HOMESCREEN_EDIT_MENU, false);

			if (this.mMenuManager.getMode() == MenuManager.LAUNCH_MODE_DEFAULT) {
				optionMenu.setGroupVisible(MENU_GROUP_DEFAULT_MENU, true);
				optionMenu.setGroupVisible(MENU_GROUP_LIST_MENU, false);
				optionMenu.setGroupVisible(MENU_GROUP_EDIT_MENU, false);

				return true;
			}

			if (this.mMenuManager.getMode() == MenuManager.EDIT_MODE) {
				optionMenu.setGroupVisible(MENU_GROUP_DEFAULT_MENU, false);
				optionMenu.setGroupVisible(MENU_GROUP_LIST_MENU, false);
				optionMenu.setGroupVisible(MENU_GROUP_EDIT_MENU, true);

				return true;
			}

			if (this.mMenuManager.getMode() == MenuManager.LAUNCH_MODE_LIST) {
				optionMenu.setGroupVisible(MENU_GROUP_DEFAULT_MENU, false);
				optionMenu.setGroupVisible(MENU_GROUP_LIST_MENU, true);
				optionMenu.setGroupVisible(MENU_GROUP_EDIT_MENU, false);

				return true;
			}
		} else {
			optionMenu.setGroupVisible(MENU_GROUP_EDIT_MENU, false);
			optionMenu.setGroupVisible(MENU_GROUP_LIST_MENU, false);
			optionMenu.setGroupVisible(MENU_GROUP_DEFAULT_MENU, false);
			optionMenu.setGroupVisible(MENU_GROUP_DEFAULT, true);
			optionMenu.setGroupVisible(MENU_GROUP_ADD, true);
		}

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case MENU_ADD:
			addItems();

			return true;

		case MENU_WALLPAPER_SETTINGS:
			startWallpaper();

			return true;

		case MENU_SEARCH:
			onSearchRequested();

			return true;

		case MENU_NOTIFICATIONS:
			showNotifications();

			return true;

		case MENU_QUICKVIEW_WORKSPACE:
			getQuickViewWorkspace().drawOpenAnimation();
			openQuickViewWorkspace();

			return true;

		case MENU_MENUEDIT:
			this.mMenuManager.setMode(MenuManager.EDIT_MODE);

			return true;

			// case MENU_QUICKVIEW_MAINMENU:
			// this.getQuickViewMainMenu().drawOpenAnimation();
			// this.openQuickViewMainMenu();
			// return true;
		case MENU_LISTVIEW:
			Log.d(TAG, "MENU_LISTVIEW");
			this.mMenuManager.setMode(MenuManager.LAUNCH_MODE_LIST);

			return true;

		case MENU_GRIDVIEW:
			this.mMenuManager.setMode(MenuManager.LAUNCH_MODE_DEFAULT);

			return true;

		case MENU_SAVE:
			menusave();
			this.mMenuManager.setMode(MenuManager.LAUNCH_MODE_DEFAULT);

			return true;

		case MENU_DISCARD:
			showDiscardMenuEdit();
			return true;

		case MENU_DESKTOP_SET: {
			Intent it = new Intent(this, PreferenceWithDesktopSetting.class);

			startActivity(it);
			break;
		}

		}

		return super.onOptionsItemSelected(item);
	}

	/**
	 * 完整
	 * 
	 * @param mode
	 */
	void saveMenuMode(int mode) {
		SharedPreferences.Editor localEditor1 = this.mPrefs.edit();
		localEditor1.putInt(PREFERENCES_MENUMODE, mode);
		localEditor1.commit();
	}

	// /**
	// * 完整
	// *
	// * @return
	// */
	// QuickViewMainMenu getQuickViewMainMenu() {
	// return this.mQuickViewMainMenu;
	// }

	/**
	 * 完整
	 * 
	 * @return
	 */
	QuickViewWorkspace getQuickViewWorkspace() {
		return this.mQuickViewWorkspace;
	}

	/**
	 * Indicates that we want global search for this activity by setting the
	 * globalSearch argument for {@link #startSearch} to true.
	 */
	@Override
	public boolean onSearchRequested() {
		startSearch(null, false, null, true);

		return true;
	}

	/**
	 * 完整
	 */
	private void addItems() {
		showAddDialog(this.mMenuAddInfo);
	}

	/**
	 * 完整
	 * 
	 * @param paramLauncherAppWidgetInfo
	 */
	public void removeAppWidget(LauncherAppWidgetInfo paramLauncherAppWidgetInfo) {
		this.mDesktopItems.remove(paramLauncherAppWidgetInfo);
		paramLauncherAppWidgetInfo.hostView = null;
	}

	/**
	 * 完整
	 * 
	 * @param paramFolderInfo
	 */
	void removeFolder(FolderInfo paramFolderInfo) {
		Long localLong = Long.valueOf(paramFolderInfo.id);
		mFolders.remove(localLong);
	}

	/**
	 * 完整
	 * 
	 * @param data
	 */
	void addAppWidget(Intent data) {
		// TODO: catch bad widget exception when sent
		int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
				-1);
		String customWidget = data.getStringExtra(EXTRA_CUSTOM_WIDGET);

		if (SEARCH_WIDGET.equals(customWidget)) {
			// We don't need this any more, since this isn't a real app widget.
			mAppWidgetHost.deleteAppWidgetId(appWidgetId);
			// add the search widget
			addSearch();
		} else {
			AppWidgetProviderInfo appWidget = mAppWidgetManager
					.getAppWidgetInfo(appWidgetId);

			if (appWidget.configure != null) {
				// Launch over to configure widget, if needed
				Intent intent = new Intent(
						AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
				intent.setComponent(appWidget.configure);
				intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
						appWidgetId);
				startActivityForResult(intent, REQUEST_CREATE_APPWIDGET);
			} else {
				// Otherwise just add it
				onActivityResult(REQUEST_CREATE_APPWIDGET, Activity.RESULT_OK,
						data);
			}
		}
	}

	/**
     * 
     */
	void addSearch() {
		final Widget info = Widget.makeSearch();
		final CellLayout.CellInfo cellInfo = this.mAddItemCellInfo;

		final int[] xy = mCellCoordinates;
		final int spanX = info.spanX;
		final int spanY = info.spanY;

		if (!findSlot(cellInfo, xy, spanX, spanY)) {
			return;
		}

		// sModel.addDesktopItem(info);
		this.addShortcut(info);
		LauncherModel.addItemToDatabase(this, info,
				LauncherSettings.Favorites.CONTAINER_DESKTOP,
				mWorkspace.getCurrentScreen(), xy[0], xy[1], false);

		final View view = mInflater.inflate(info.layoutResource, null);
		view.setTag(info);

		Search search = (Search) view.findViewById(R.id.widget_search);
		search.setLauncher(this);

		mWorkspace.addInCurrentScreen(view, xy[0], xy[1], info.spanX, spanY);
	}

	/**
	 * 完整
	 * 
	 * @param intent
	 * @param requestCodeApplication
	 * @param requestCodeShortcut
	 */
	void processShortcut(Intent intent, int requestCodeApplication,
			int requestCodeShortcut) {
		// Handle case where user selected "Applications"
		String applicationName = getResources().getString(
				R.string.group_applications);
		String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);

		if ((applicationName != null) && applicationName.equals(shortcutName)) {
			Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
			mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);

			Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
			pickIntent.putExtra(Intent.EXTRA_INTENT, mainIntent);
			startActivityForResult(pickIntent, requestCodeApplication);
		} else {
			startActivityForResult(intent, requestCodeShortcut);
		}
	}

	/**
	 * 完整
	 * 
	 * @param intent
	 */
	void addLiveFolder(Intent intent) {
		// Log.e(TAG, "addLiveFolder");
		// Handle case where user selected "Folder"
		String folderName = getResources().getString(R.string.group_folder);
		String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);

		if ((folderName != null) && folderName.equals(shortcutName)) {
			addUserFolder();
		} else {
			startActivityForResult(intent, REQUEST_CREATE_LIVE_FOLDER);
		}
	}

	/**
	 * 完整
	 */
	void addUserFolder() {
		// Log.e(TAG, "addFolder");
		UserFolderInfo localUserFolderInfo = new UserFolderInfo();
		CharSequence localCharSequence = getText(R.string.folder_name);
		localUserFolderInfo.title = localCharSequence;

		CellLayout.CellInfo localCellInfo = this.mAddItemCellInfo;
		localCellInfo.screen = this.mWorkspace.getCurrentScreen();

		if (!findSingleSlot(localCellInfo)) {
			return;
		}

		LauncherModel.addItemToDatabase(this, localUserFolderInfo,
				LauncherSettings.Favorites.CONTAINER_DESKTOP,
				this.mWorkspace.getCurrentScreen(), localCellInfo.cellX,
				localCellInfo.cellY, false);
		mFolders.put(localUserFolderInfo.id, localUserFolderInfo);

		int n = this.mWorkspace.getCurrentScreen();
		ViewGroup localViewGroup = (ViewGroup) this.mWorkspace.getChildAt(n);
		FolderIcon localFolderIcon = FolderIcon.fromXml(R.layout.folder_icon,
				this, localViewGroup, localUserFolderInfo);
		this.mWorkspace.addInCurrentScreen(localFolderIcon,
				localCellInfo.cellX, localCellInfo.cellY, 1, 1,
				isWorkspaceLocked());
	}

	/**
	 * 完整
	 * 
	 * @param data
	 * @param cellInfo
	 */
	private void completeAddLiveFolder(Intent data, CellLayout.CellInfo cellInfo) {
		cellInfo.screen = mWorkspace.getCurrentScreen();

		if (!findSingleSlot(cellInfo)) {
			return;
		}

		final LiveFolderInfo info = addLiveFolder(this, data, cellInfo, false);

		if (!mRestoring) {
			int j = this.mWorkspace.getCurrentScreen();
			ViewGroup localViewGroup = (ViewGroup) mWorkspace.getChildAt(j);
			LiveFolderIcon localLiveFolderIcon = LiveFolderIcon.fromXml(
					R.layout.live_folder_icon, this, localViewGroup, info);
			Workspace localWorkspace2 = this.mWorkspace;
			int k = cellInfo.cellX;
			int m = cellInfo.cellY;
			localWorkspace2.addInCurrentScreen(localLiveFolderIcon, k, m, 1, 1,
					isWorkspaceLocked());
		}
	}

	static LiveFolderInfo addLiveFolder(Context context, Intent data,
			CellLayout.CellInfo cellInfo, boolean notify) {
		Intent baseIntent = data
				.getParcelableExtra(LiveFolders.EXTRA_LIVE_FOLDER_BASE_INTENT);
		String name = data.getStringExtra(LiveFolders.EXTRA_LIVE_FOLDER_NAME);

		Drawable icon = null;
		boolean filtered = false;
		Intent.ShortcutIconResource iconResource = null;

		Parcelable extra = data
				.getParcelableExtra(LiveFolders.EXTRA_LIVE_FOLDER_ICON);

		if ((extra != null) && extra instanceof Intent.ShortcutIconResource) {
			try {
				iconResource = (Intent.ShortcutIconResource) extra;

				final PackageManager packageManager = context
						.getPackageManager();
				Resources resources = packageManager
						.getResourcesForApplication(iconResource.packageName);
				final int id = resources.getIdentifier(
						iconResource.resourceName, null, null);
				icon = resources.getDrawable(id);
			} catch (Exception e) {
				w(TAG, "Could not load live folder icon: " + extra);
			}
		}

		if (icon == null) {
			icon = context.getResources().getDrawable(
					R.drawable.ic_launcher_folder);
		}

		final LiveFolderInfo info = new LiveFolderInfo();
		Bitmap localBitmap = Utilities.createIconBitmap(icon, context, null);
		info.icon = localBitmap;
		// info.filtered = filtered;
		info.title = name;
		info.iconResource = iconResource;
		info.uri = data.getData();
		info.baseIntent = baseIntent;
		info.displayMode = data.getIntExtra(
				LiveFolders.EXTRA_LIVE_FOLDER_DISPLAY_MODE,
				LiveFolders.DISPLAY_MODE_GRID);

		LauncherModel.addItemToDatabase(context, info,
				LauncherSettings.Favorites.CONTAINER_DESKTOP, cellInfo.screen,
				cellInfo.cellX, cellInfo.cellY, notify);
		// sModel.addFolder(info);
		mFolders.put(info.id, info);

		return info;
	}

	private boolean findSingleSlot(CellLayout.CellInfo cellInfo) {
		final int[] xy = new int[2];

		if (findSlot(cellInfo, xy, 1, 1)) {
			cellInfo.cellX = xy[0];
			cellInfo.cellY = xy[1];

			return true;
		}

		return false;
	}

	private boolean findSlot(CellLayout.CellInfo cellInfo, int[] xy, int spanX,
			int spanY) {
		if (!cellInfo.findCellForSpan(xy, spanX, spanY)) {
			boolean[] occupied = (mSavedState != null) ? mSavedState
					.getBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS)
					: null;
			cellInfo = mWorkspace.findAllVacantCells(occupied);

			Toast.makeText(this, getString(R.string.out_of_space),
					Toast.LENGTH_SHORT).show();

			return false;
		}

		return true;
	}

	/**
	 * 完整
	 */
	private void showNotifications() {
		final StatusBarManager statusBar = (StatusBarManager) getSystemService(STATUS_BAR_SERVICE);

		if (statusBar != null) {
			statusBar.expand();
		}
	}

	/**
	 * 完整
	 */
	private void startWallpaper() {
		final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);
		Intent chooser = Intent.createChooser(pickWallpaper,
				getText(R.string.chooser_wallpaper));
		WallpaperManager wm = (WallpaperManager) getSystemService(Context.WALLPAPER_SERVICE);
		WallpaperInfo wi = wm.getWallpaperInfo();

		if ((wi != null) && (wi.getSettingsActivity() != null)) {
			LabeledIntent li = new LabeledIntent(getPackageName(),
					R.string.configure_wallpaper, 0);
			li.setClassName(wi.getPackageName(), wi.getSettingsActivity());
			chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { li });
		}

		startActivityForResult(chooser, REQUEST_PICK_WALLPAPER);
	}

	/**
	 * 完整 Registers various intent receivers. The current implementation
	 * registers only a wallpaper intent receiver to let other applications
	 * change the wallpaper.
	 */
	private void registerIntentReceivers() {
		IntentFilter localIntentFilter1 = new IntentFilter(
				Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
		registerReceiver(mCloseSystemDialogsReceiver, localIntentFilter1);

		IntentFilter localIntentFilter3 = new IntentFilter();
		localIntentFilter3.addAction(Intent.ACTION_WALLPAPER_CHANGED);
		registerReceiver(mWallpaperChangedReceiver, localIntentFilter3);
	}

	/**
	 * 完整 Registers various content observers. The current implementation
	 * registers only a favorites observer to keep track of the favorites
	 * applications.
	 */
	private void registerContentObservers() {
		ContentResolver resolver = getContentResolver();
		resolver.registerContentObserver(
				LauncherProvider.CONTENT_APPWIDGET_RESET_URI, true,
				mWidgetObserver);
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		// if (event.getAction() == KeyEvent.ACTION_DOWN) {
		// switch (event.getKeyCode()) {
		// case KeyEvent.KEYCODE_BACK:
		// return true;

		// case KeyEvent.KEYCODE_HOME:
		// return true;
		// }
		// } else
		if (event.getAction() == KeyEvent.ACTION_DOWN) {
			switch (event.getKeyCode()) {
			case KeyEvent.KEYCODE_BACK: {
				if (!event.isCanceled()) {
					mWorkspace.dispatchKeyEvent(event);

					if (mMenuManager.getMode() == 2) {
						menusave();
						mMenuManager.setMode(0);
						return true;
					}

					closeDrawer();
					closeFolder();

					if ((this.mQuickViewWorkspace.isOpened())
							|| (this.mStateQuickNavigation == 0)) {
						if (this.mQuickViewWorkspace.isAnimating()) {
							return true;
						}

						cancelRemovePage();
						this.mQuickViewWorkspace.cancelDrag();
						this.mQuickViewWorkspace.drawCloseAnimation();
						this.mQuickViewWorkspace.invalidate();

						return true;
					}

					// if ((this.mQuickViewMainMenu.isOpened())
					// || (this.mStateQuickNavigation == 1)) {
					// this.mQuickViewMainMenu.cancelDrag();
					// this.mQuickViewMainMenu.drawCloseAnimation();
					// this.mQuickViewMainMenu.invalidate();
					//
					// return true;
					// }

					if (this.mQuickViewWorkspace.isOpened()) {
						closeQuickViewWorkspace();
					}

					// if (this.mQuickViewMainMenu.isOpened()) {
					// closeQuickViewMainMenu();
					// }
				}

				return true;
			}

			case KeyEvent.KEYCODE_HOME:
				return true;
			}
		}

		return super.dispatchKeyEvent(event);
	}

	private void showProgressDialog() {
		this.mDialog = new ProgressDialog(this);
		mDialog.setMessage(getString(R.string.uninstall));
		mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		mDialog.show();
	}

	/**
	 * 完整
	 */
	private void uninstallPackage() {
		showProgressDialog();

		Runnable r = new Runnable() {
			public void run() {
				mMenuManager.lock();
				PackageDeleteObserver localPackageDeleteObserver = new PackageDeleteObserver();

				try {
					PackageManager localPackageManager = getPackageManager();
					localPackageManager.deletePackage(mUninstallPackageName,
							localPackageDeleteObserver, 0);
					mUninstallPackageName = null;

					// Log.e(TAG,"uninstallPackage end,  before invalidate");

					if (mMenuManager.getMode() == MenuManager.EDIT_MODE) {
						menusave();
					}
					mDragLayer.invalidate();

					// Log.e(TAG,"after invalidate");
					if (mDialog != null) {
						mDialog.cancel();
						mDialog.dismiss();
					}
					return;
				} catch (Exception e) {
					e.printStackTrace();
					mMenuManager.unlock();
				}
			}
		};

		new Handler().post(r);
	}

	void uninstallPackage(String paramString) {
		mUninstallPackageName = paramString;
		uninstallPackage();
	}

	private void closeDrawer() {
		closeDrawer(true);
	}

	/**
	 * 完整
	 * 
	 * @param animated
	 */
	private void closeDrawer(boolean animated) {
		MenuManager localMenuManager = this.mMenuManager;

		if (localMenuManager.isOpened()) {
			if (localMenuManager.getMode() == 2) {
				menusave();
				localMenuManager.setMode(0);
			}
			if (animated) {
				localMenuManager.animateClose();
			}
			// else {
			// localMenuManager.close();
			// }

			if (localMenuManager.hasFocus()) {
				Workspace localWorkspace = this.mWorkspace;
				int i = this.mWorkspace.getCurrentScreen();
				localWorkspace.getChildAt(i).requestFocus();
			}

		}
	}

	private void closeFolder() {
		Folder folder = mWorkspace.getOpenFolder();

		if (folder != null) {
			closeFolder(folder);
		}
	}

	/**
	 * 完整
	 */
	void menudiscard() {
		this.mMenuManager.discardMenuEdit();
		this.mMenuManager.setMode(MenuManager.LAUNCH_MODE_DEFAULT);
		this.mAppShortcutZone.updateApplications();
	}

	/**
	 * 没有问题，在保存的时候会校正不正确的值.
	 */
	void menusave() {
		Log.d("Launcher", "Launcher - menusave");
		this.mMenuManager.stopUpdateDB();

		// 首先更新保存 AppShortcutZone
		int shortcutCount = this.mAppShortcutZone.getChildCount();

		for (int i = 0; i < shortcutCount; i++) {
			Object childObject = this.mAppShortcutZone.getChildAt(i).getTag();

			if ((childObject instanceof ApplicationInfo)) {
				ApplicationInfo localApplicationInfo = (ApplicationInfo) childObject;

				if ((localApplicationInfo.topNum == i)
						&& (localApplicationInfo.pageNum == -1)
						&& (localApplicationInfo.cellNum == -1)) {
					localApplicationInfo.editTopNum = i;
					localApplicationInfo.editPageNum = -1;
					localApplicationInfo.editCellNum = -1;

					continue;
				}

				localApplicationInfo.topNum = i;
				localApplicationInfo.pageNum = -1;
				localApplicationInfo.cellNum = -1;
				localApplicationInfo.isUpdated = false;
				localApplicationInfo.editTopNum = i;
				localApplicationInfo.editPageNum = -1;
				localApplicationInfo.editCellNum = -1;
				LauncherModel.updateAppToDatabase(this, localApplicationInfo);
			}
		}

		int menuCount = this.mMenuManager.getChildCount();

		for (int i = 0; i < menuCount; i++) {
			AppMenu localAppMenu = (AppMenu) this.mMenuManager.getChildAt(i);
			int appCount = localAppMenu.getChildCount();

			for (int j = 0; j < appCount; j++) {
				Object localObject = localAppMenu.getChildAt(j).getTag();

				if ((localObject instanceof ApplicationInfo)) {
					ApplicationInfo localApplicationInfo = (ApplicationInfo) localObject;

					// // 暂时注释

					// if ((localApplicationInfo.topNum == -1)
					// && (localApplicationInfo.pageNum == i)
					// && (localApplicationInfo.cellNum == j)) {
					// localApplicationInfo.editTopNum =
					// localApplicationInfo.topNum;
					// localApplicationInfo.editPageNum =
					// localApplicationInfo.pageNum;
					// localApplicationInfo.editCellNum =
					// localApplicationInfo.cellNum;
					// continue;
					// }
					localApplicationInfo.topNum = -1;
					localApplicationInfo.pageNum = i;
					localApplicationInfo.cellNum = j;
					localApplicationInfo.isUpdated = false;
					localApplicationInfo.editTopNum = -1;
					localApplicationInfo.editPageNum = i;
					localApplicationInfo.editCellNum = j;
					LauncherModel.updateAppToDatabase(this,
							localApplicationInfo);
				}
			}
		}

		// this.mMenuManager.printMenuManager();
		// Log.e(TAG, "after menusave");
		// this.mMenuManager.printApplicationsAdapter();
	}

	void dumpDatabase() {
		final ContentResolver cr = getContentResolver();
		Cursor c = cr.query(LauncherSettings.Apps.CONTENT_URI, null, null,
				null, null);
		DatabaseUtils.dumpCursor(c);
	}

	// /**
	// * 完整
	// */
	// void closeQuickViewMainMenu() {
	// if (!this.mQuickViewMainMenu.isOpened()) {
	// return;
	// }
	//
	// getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
	// this.mQuickViewMainMenu.close();
	//
	// int i = this.mQuickViewMainMenu.getCurrentPage();
	//
	// if ((i >= 0) && (i < this.mMenuManager.getChildCount())) {
	// } else {
	// i = this.mMenuManager.getCurrentScreen();
	// }
	//
	// if (this.mMenuManager.getCurrentScreen() != i) {
	// this.mMenuManager.setCurrentScreen(i);
	// }
	//
	// this.mMenuManager.setVisibility(View.VISIBLE);
	// this.mAppShortcutZone.setVisibility(View.VISIBLE);
	//
	// int m = this.mMenuManager.getCurrentScreen();
	// mMenuManager.getChildAt(m).requestFocus();
	// this.mMenuManager.computeScroll();
	//
	// int n = this.mMenuManager.getCurrentScreen();
	// int i1 = this.mMenuManager.getWidth();
	// int i2 = n * i1;
	// mMenuManager.scrollTo(i2, 0);
	// }

	void closeFolder(Folder folder) {
		folder.getInfo().opened = false;

		ViewGroup parent = (ViewGroup) folder.getParent();

		if (parent != null) {
			parent.removeView(folder);
		}

		folder.onClose();
	}

	/**
	 * 有问题，没有地方调用
	 * 
	 * @return
	 */
	private int createBlankPage() {
		// if ((this.mBlankScreen[0] != -1) || (this.mBlankScreen[1] != -1))
		// {
		// return -1;
		// }
		int j = this.mWorkspace.getChildCount();
		int k = SCREEN_COUNT;

		if (j < k) {
			View v = LayoutInflater.from(this).inflate(
					R.layout.workspace_screen, mWorkspace, false);
			CellLayout localCellLayout = (CellLayout) v;
			localCellLayout.setOnLongClickListener(this);
			mWorkspace.addView(localCellLayout);

			int m = getCellLayoutId(j);
			localCellLayout.setId(m);
			this.mBlankScreen[0] = j;
			saveScreenInfo();

			return j;
		} else {
			return -1;
		}
	}

	/**
	 * 不完整
	 * 
	 * @param paramInt1
	 * @param paramInt2
	 */
	private void prepareWidgetPreview(int paramInt1, int paramInt2) {
		this.mMenuManager.lock();

		if (paramInt1 == 2) {
			previewAppWidget();
			// this.mWorkspace.initAddWidget();
			this.mWidgetPreview.setVisibility(0);
			this.mDragLayer.invalidate();

			if (this.mBlankScreen[0] == -1) {
			}

			// break label87;
			// i = this.mBlankScreen[0];
		}
	}

	private void previewAppWidget() {
		if ((this.mWidgetId == -1) || (this.mAppWidgetInfo == null)) {
			cancelAddWidget();
		} else {
			int i = this.mWidgetId;
			int[] arrayOfInt = this.mSpans;
			AppWidgetProviderInfo localAppWidgetProviderInfo = this.mAppWidgetInfo;
			LauncherAppWidgetInfo localLauncherAppWidgetInfo = new LauncherAppWidgetInfo(
					i);
			int j = arrayOfInt[0];
			localLauncherAppWidgetInfo.spanX = j;

			int k = arrayOfInt[1];
			localLauncherAppWidgetInfo.spanY = k;

			AppWidgetHostView localAppWidgetHostView1 = this.mAppWidgetHost
					.createView(this, i, localAppWidgetProviderInfo);
			localLauncherAppWidgetInfo.hostView = localAppWidgetHostView1;
			localLauncherAppWidgetInfo.hostView.setAppWidget(i,
					localAppWidgetProviderInfo);
			localLauncherAppWidgetInfo.hostView
					.setTag(localLauncherAppWidgetInfo);

			int m = getResources().getDimensionPixelSize(R.dimen.cell_width);
			int n = getResources().getDimensionPixelSize(R.dimen.cell_height);
			WidgetPreview localWidgetPreview = this.mWidgetPreview;
			AppWidgetHostView localAppWidgetHostView2 = localLauncherAppWidgetInfo.hostView;
			int i1 = localLauncherAppWidgetInfo.spanX * m;
			int i2 = localLauncherAppWidgetInfo.spanY * n;
			ViewGroup.LayoutParams localLayoutParams = new ViewGroup.LayoutParams(
					i1, i2);
			localWidgetPreview.addView(localAppWidgetHostView2,
					localLayoutParams);
			this.mWidgetPreview.setVisibility(View.VISIBLE);
			this.mLauncherAppWidgetInfo = localLauncherAppWidgetInfo;
		}
	}

	/**
	 * 完整
	 */
	void removePage() {
		this.mIsDeletePopup = false;
		this.mQuickViewWorkspace.removeScreen();
		this.mWaitingForResult = false;
	}

	/**
	 * 完整
	 * 
	 * @param info
	 */
	public void removeShortcut(ShortcutInfo info) {
		this.mDesktopItems.remove(info);
	}

	/**
	 * Re-listen when widgets are reset.
	 */
	private void onAppWidgetReset() {
		mAppWidgetHost.startListening();
	}

	/**
	 * 完整
	 * 
	 * @param color
	 */
	public void setBackgroundNotification(int color) {
		findViewById(android.R.id.content).setBackgroundColor(color);
	}

	// /**
	// * 完整
	// */
	// public void openQuickViewMainMenu() {
	// if (!this.mMenuManager.isOpened()) {
	// return;
	// }
	//

	// this.mAppShortcutZone.setVisibility(View.GONE);
	// setBackgroundNotification(Color.TRANSPARENT);
	// this.mMenuManager.invalidate();
	//
	// if ((this.mMenuManager.getChildCount() == 0)
	// && (this.mMenuScreenCount > 0)) {
	// mQuickViewMainMenu.initScreen(this.mMenuScreenCount);
	// } else {
	// int j = this.mMenuManager.getChildCount();
	// mQuickViewMainMenu.initScreen(j);
	// }
	//
	// closeOptionsMenu();
	// this.mQuickViewMainMenu.open();
	// }

	int getCellLayoutId(int index) {
		switch (index) {
		case 0:
			return R.id.cell1;

		case 1:
			return R.id.cell2;

		case 2:
			return R.id.cell3;

		case 3:
			return R.id.cell4;

		case 4:
			return R.id.cell5;

		case 5:
			return R.id.cell6;

		case 6:
			return R.id.cell7;

		default:
			return -1;
		}
	}

	/**
	 * Launches the intent referred by the clicked shortcut.
	 * 
	 * @param v
	 *            The view representing the clicked shortcut.
	 */
	public void onClick(View v) {
		Object tag = v.getTag();
		if (tag instanceof ShortcutInfo) {
			// Open shortcut
			final Intent intent = ((ShortcutInfo) tag).intent;
			int[] pos = new int[2];
			v.getLocationOnScreen(pos);
			intent.setSourceBounds(new Rect(pos[0], pos[1], pos[0]
					+ v.getWidth(), pos[1] + v.getHeight()));
			startActivitySafely(intent);
		} else if (tag instanceof FolderInfo) {
			handleFolderClick((FolderInfo) tag);
		}
	}

	void startActivitySafely(Intent intent) {
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

		try {
			startActivity(intent);
		} catch (ActivityNotFoundException e) {
			Toast.makeText(this, R.string.activity_not_found,
					Toast.LENGTH_SHORT).show();
		} catch (SecurityException e) {
			Toast.makeText(this, R.string.activity_not_found,
					Toast.LENGTH_SHORT).show();
			e(TAG,
					"Launcher does not have the permission to launch "
							+ intent
							+ ". Make sure to create a MAIN intent-filter for the corresponding activity "
							+ "or use the exported attribute for this activity.",
					e);
		}
	}

	void startActivitySafely(Intent intent, Object paramObject) {
		this.startActivitySafely(intent);
	}

	private void handleFolderClick(FolderInfo folderInfo) {
		if (!folderInfo.opened) {
			// Close any open folder
			closeFolder();
			// Open the requested folder
			openFolder(folderInfo);
		} else {
			// Find the open folder...
			Folder openFolder = mWorkspace.getFolderForTag(folderInfo);
			int folderScreen;

			if (openFolder != null) {
				folderScreen = mWorkspace.getScreenForView(openFolder);
				// .. and close it
				closeFolder(openFolder);

				if (folderScreen != mWorkspace.getCurrentScreen()) {
					// Close any folder open on the current screen
					closeFolder();
					// Pull the folder onto this screen
					openFolder(folderInfo);
				}
			}
		}
	}

	DeleteZone getDeleteZone() {
		return this.mDeleteZone;
	}

	/**
	 * Opens the user fodler described by the specified tag. The opening of the
	 * folder is animated relative to the specified View. If the View is null,
	 * no animation is played.
	 * 
	 * @param folderInfo
	 *            The FolderInfo describing the folder to open.
	 */
	private void openFolder(FolderInfo folderInfo) {
		Folder openFolder;

		if (folderInfo instanceof UserFolderInfo) {
			openFolder = UserFolder.fromXml(this);
		} else if (folderInfo instanceof LiveFolderInfo) {
			openFolder = com.android.launcher3.LiveFolder.fromXml(this,
					folderInfo);
		} else {
			return;
		}

		openFolder.setDragger(mDragLayer);
		openFolder.setLauncher(this);

		openFolder.bind(folderInfo);
		folderInfo.opened = true;

		mWorkspace.addInScreen(openFolder, folderInfo.screen, 0, 0, 4, 4);
		openFolder.onOpen();
	}

	/**
	 * 完整 Returns true if the workspace is being loaded. When the workspace is
	 * loading, no user interaction should be allowed to avoid any conflict.
	 * 
	 * @return True if the workspace is locked, false otherwise.
	 */
	boolean isWorkspaceLocked() {
		// Log.e(TAG, "isWorkspaceLocked");
		// Log.e(TAG, "this.mWorkspaceLoading " + this.mWorkspaceLoading);
		// Log.e(TAG, "this.mWaitingForResult " + this.mWaitingForResult);
		if ((this.mWorkspaceLoading) || (this.mWaitingForResult)) {
			return true;
		}
		return false;
	}

	/**
	 * 完整
	 */
	public boolean onLongClick(View v) {
		// Log.e(TAG, "onLongClick");
		if (isWorkspaceLocked()) {
			Log.e(TAG, "WorkspaceLocked is true");
			return false;
		}

		if (!(v instanceof CellLayout)) {
			v = (View) v.getParent();
		}

		CellLayout.CellInfo cellInfo = (CellLayout.CellInfo) v.getTag();

		// This happens when long clicking an item with the dpad/trackball
		if (cellInfo == null) {
			return true;
		}

		if (mWorkspace.allowLongPress()) {
			if (cellInfo.cell == null) {
				if (cellInfo.valid) {
					// Log.e(TAG, "showAddDialog");
					// User long pressed on empty space
					mWorkspace.setAllowLongPress(false);
					showAddDialog(cellInfo);
				}
			} else {
				if (!(cellInfo.cell instanceof Folder)) {
					// User long pressed on an item
					mWorkspace.startDrag(cellInfo);
				}
			}
		}
		// 调试用
		else {
			Log.e(TAG, "mWorkspace not allowLongPress ");

		}

		return true;
	}

	// static LauncherModel getModel() {
	void closeAllApplications() {
		this.mMenuManager.close();
	}

	// View getDrawerHandle() {
	Workspace getWorkspace() {
		return mWorkspace;
	}

	// GridView getApplicationsGrid() {
	@Override
	protected Dialog onCreateDialog(int id) {

		switch (id) {
		case DIALOG_CREATE_SHORTCUT:
			// Log.e(TAG,"onCreateDialog CreateShortcut  000000000000");
			return new CreateShortcut().createDialog();

		case DIALOG_RENAME_FOLDER:
			// Log.e(TAG,"onCreateDialog RenameFolder  1111111111");
			return new RenameFolder().createDialog();

		case DIALOG_DELETE_APPLICATION:
			return new TextDialog().createDialog(id);

		case DIALOG_DISCARD_MENUEDIT:
			// Log.e(TAG,"onCreateDialog DIALOG_DISCARD_MENUEDIT  222222222");
			return new TextDialog().createDialog(id);

		case DIALOG_DELETE_WORKSCREEN:
			return new TextDialog().createDialog(id);
		}

		return super.onCreateDialog(id);
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		// Log.e(TAG,"onPrepareDialog "+ id );
		switch (id) {
		case DIALOG_CREATE_SHORTCUT:
			// this.mWaitingForResult=true;
			break;

		case DIALOG_RENAME_FOLDER:

			if (mFolderInfo != null) {
				EditText input = (EditText) dialog
						.findViewById(R.id.folder_name);
				final CharSequence text = mFolderInfo.title;
				input.setText(text);
				input.setSelection(0, text.length());
			}

			break;
		}
	}

	void showDiscardMenuEdit() {
		showDialog(DIALOG_DISCARD_MENUEDIT);
	}

	void showRenameDialog(FolderInfo info) {
		mFolderInfo = info;
		// mWaitingForResult = true;
		showDialog(DIALOG_RENAME_FOLDER);
	}

	private void showAddDialog(CellLayout.CellInfo cellInfo) {
		this.mAddItemCellInfo = cellInfo;
		// mWaitingForResult = true;
		// Log.e(TAG,"mWaitingForResult true   44444");
		showDialog(DIALOG_CREATE_SHORTCUT);
	}

	void showDeleteApplication(String packageName) {
		mUninstallPackageName = packageName;
		showDialog(DIALOG_DELETE_APPLICATION);
	}

	private void pickShortcut(int requestCode, int title) {
		Bundle bundle = new Bundle();

		ArrayList<String> shortcutNames = new ArrayList<String>();
		shortcutNames.add(getString(R.string.group_applications));
		bundle.putStringArrayList(Intent.EXTRA_SHORTCUT_NAME, shortcutNames);

		ArrayList<ShortcutIconResource> shortcutIcons = new ArrayList<ShortcutIconResource>();
		shortcutIcons.add(ShortcutIconResource.fromContext(Launcher.this,
				R.drawable.ic_launcher_application));
		bundle.putParcelableArrayList(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
				shortcutIcons);

		Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
		pickIntent.putExtra(Intent.EXTRA_INTENT, new Intent(
				Intent.ACTION_CREATE_SHORTCUT));
		pickIntent.putExtra(Intent.EXTRA_TITLE, getText(title));
		pickIntent.putExtras(bundle);

		startActivityForResult(pickIntent, requestCode);
	}

	boolean isAddWidgetState() {
		if (this.mAddWidgetType != 0) {
			return true;
		}

		return false;
	}

	public int getStateQuickNavigation() {
		return this.mStateQuickNavigation;
	}

	public void showDeleteWorkScreen() {
		this.mIsDeletePopup = true;
		showDialog(DIALOG_DELETE_WORKSCREEN);
	}

	/**
	 * 完整
	 */
	void cancelRemovePage() {
		this.mIsDeletePopup = false;
		this.mQuickViewWorkspace.cancelDeleteView();
	}

	boolean checkMoreContents() {
		Intent localIntent = new Intent(
				"com.sec.android.app.morewidget.action.APP_MORECONTENTS");
		List localList = getPackageManager().queryIntentActivities(localIntent,
				0);

		if ((localList != null) && (localList.size() > 0)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 完整
	 */
	public void bindAllApplications(ArrayList<ApplicationInfo> apps) {
		// Log.e(TAG, "bindAllApplications");
		// Log.e(TAG, "bindAllApplications count "+ apps.size());
		// Log.e(TAG, ""+apps.toString());
		this.mMenuManager.setApps(apps);
		this.mMainMenuLoading = false;
		Log.d("Launcher", "Main menu binding finished");
	}

	public void addApplication(ApplicationInfo appInfo) {
		this.mMenuManager.addApplication(appInfo);
	}

	/**
	 * 完整
	 * 
	 * @param apps
	 */
	public void bindAppsAdded(ArrayList<ApplicationInfo> apps) {
		// Log.e(TAG, "bindAppsAdded");

		if (this.mDestroyed || (apps == null)) {
			return;
		}

		removeDialog(DIALOG_CREATE_SHORTCUT);

		int count = apps.size();

		// Log.e(TAG, "count " + count);

		for (int i = 0; i < count; i++) {
			ApplicationInfo app = (ApplicationInfo) apps.get(i);
			LauncherModel.addAppToDatabase(this, app);

			// Log.e(TAG, "pageNum" +app.pageNum);
			// Log.e(TAG, "cellNum " +app.cellNum);
			// Log.e(TAG, "topNum" +app.topNum);

		}

		this.mMenuManager.addApps(apps);
		this.mMainMenuLoading = false;
	}

	/**
	 * 完整
	 * 
	 * @param apps
	 */
	public void bindAppsRemoved(ArrayList<ApplicationInfo> apps) {
		// Log.e("Launcher", TAG + " bindAppsRemoved");

		if (this.mDestroyed || (apps == null)) {
			return;
		}

		removeDialog(DIALOG_CREATE_SHORTCUT);

		for (ApplicationInfo localApplicationInfo : apps) {
			// Log.e(TAG,""+ localApplicationInfo.title);
			LauncherModel.removeAppToDatabase(this, localApplicationInfo);
		}

		this.mWorkspace.removeItems(apps);
		this.mMenuManager.removeApps(apps, true);
	}

	/**
	 * 完整
	 * 
	 * @param apps
	 */
	public void bindAppsUpdated(ArrayList<ApplicationInfo> apps) {
		// Log.e(TAG, "bindAppsUpdated");
		if (this.mDestroyed || (apps == null)) {
			return;
		}
		removeDialog(DIALOG_CREATE_SHORTCUT);
		this.mWorkspace.updateShortcuts(apps);
		this.mMenuManager.updateApps(apps);
	}

	/**
	 * 完整
	 * 
	 * @param paramHashMap
	 */
	public void bindFolders(HashMap<Long, FolderInfo> paramHashMap) {
		mFolders.clear();
		mFolders.putAll(paramHashMap);
	}

	public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end) {
		Log.d("Model", "bindItems-startIndex=" + start + ",endIndex=" + end);

		for (int i = start; i < end; i++) {
			ItemInfo localItemInfo1 = (ItemInfo) shortcuts.get(i);
			this.mDesktopItems.add(localItemInfo1);

			switch (localItemInfo1.itemType) {
			case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
			case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: {
				ShortcutInfo localShortcutInfo3 = (ShortcutInfo) localItemInfo1;
				ShortcutInfo localShortcutInfo4 = localShortcutInfo3;
				View localView = this.createShortcut(localShortcutInfo4);
				int n = localItemInfo1.screen;
				int i1 = localItemInfo1.cellX;
				int i2 = localItemInfo1.cellY;
				this.mWorkspace.addInScreen(localView, n, i1, i2, 1, 1,
						!mDesktopLocked);

				break;
			}

			case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER: {
				int i3 = this.mWorkspace.getCurrentScreen();
				ViewGroup localViewGroup1 = (ViewGroup) this.mWorkspace
						.getChildAt(i3);
				UserFolderInfo localUserFolderInfo1 = (UserFolderInfo) localItemInfo1;
				Launcher localLauncher2 = this;
				FolderIcon localFolderIcon = FolderIcon.fromXml(
						R.layout.folder_icon, localLauncher2, localViewGroup1,
						localUserFolderInfo1);
				int i5 = localItemInfo1.screen;
				int i6 = localItemInfo1.cellX;
				int i7 = localItemInfo1.cellY;
				this.mWorkspace.addInScreen(localFolderIcon, i5, i6, i7, 1, 1,
						!mDesktopLocked);

				break;
			}

			case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER: {
				int i8 = this.mWorkspace.getCurrentScreen();
				ViewGroup localViewGroup3 = (ViewGroup) this.mWorkspace
						.getChildAt(i8);
				LiveFolderInfo localLiveFolderInfo1 = (LiveFolderInfo) localItemInfo1;
				LiveFolderIcon localLiveFolderIcon = LiveFolderIcon.fromXml(
						R.layout.live_folder_icon, this, localViewGroup3,
						localLiveFolderInfo1);
				int i10 = localItemInfo1.screen;
				int i11 = localItemInfo1.cellX;
				int i12 = localItemInfo1.cellY;
				this.mWorkspace.addInScreen(localLiveFolderIcon, i10, i11, i12,
						1, 1, !mDesktopLocked);

				break;
			}

			case LauncherSettings.Favorites.ITEM_TYPE_WIDGET_SEARCH: {
				final int screen = this.mWorkspace.getCurrentScreen();
				final View view = mInflater.inflate(R.layout.widget_search,
						(ViewGroup) this.mWorkspace.getChildAt(screen),
						!mDesktopLocked);

				Search search = (Search) view.findViewById(R.id.widget_search);
				search.setLauncher(this);

				final Widget widget = (Widget) localItemInfo1;
				view.setTag(widget);
				this.mWorkspace.addWidget(view, widget, !mDesktopLocked);

				break;
			}
			}
		}

		this.mWorkspace.requestLayout();
	}

	public void finishBindingAllWorkspaceItems() {
		if (this.mSavedState != null) {
			if (!this.mWorkspace.hasFocus()) {
				int i = this.mWorkspace.getCurrentScreen();
				this.mWorkspace.getChildAt(i).requestFocus();
			}

			long[] arrayOfLong1 = this.mSavedState
					.getLongArray("launcher.user_folder");

			if (arrayOfLong1 != null) {
				long[] arrayOfLong2 = arrayOfLong1;
				int j = arrayOfLong2.length;
				int k = 0;

				while (k < j) {
					long l = arrayOfLong2[k];
					HashMap localHashMap = mFolders;
					Long localLong = Long.valueOf(l);
					FolderInfo localFolderInfo = (FolderInfo) localHashMap
							.get(localLong);

					if (localFolderInfo != null) {
						openFolder(localFolderInfo);
					}

					k += 1;
				}

				Folder localFolder = this.mWorkspace.getOpenFolder();

				if (localFolder != null) {
					localFolder.requestFocus();
				}
			}

			this.mSavedState = null;
		}

		if (this.mSavedInstanceState != null) {
			super.onRestoreInstanceState(this.mSavedInstanceState);
			this.mSavedInstanceState = null;
		}

		this.mWorkspaceLoading = false;
		Log.d("Launcher", "Workspace binding finished");

		// Handler localHandler1 = this.mHandler;
		// Runnable localRunnable1 = this.mRunBadgeChanged;
		// localHandler1.removeCallbacks(localRunnable1);
		// Handler localHandler2 = this.mHandler;
		// Runnable localRunnable2 = this.mRunBadgeChanged;
		// boolean bool3 = localHandler2.post(localRunnable2);
	}

	/**
	 * 不完整
	 */
	int getAdjacentBlankScreen(int paramInt) {
		return -1;
	}

	/**
	 * 完整
	 * 
	 * @return
	 */
	int loadMenuMode() {
		return this.mPrefs.getInt(PREFERENCES_MENUMODE, 0);
	}

	boolean isAllPageSlot(int paramInt) {
		this.mBlankScreen[0] = -1;
		this.mBlankScreen[1] = -1;
		getAdjacentBlankScreen(paramInt);

		return false;
	}

	public void finishBindingAppWidgets() {
		Log.d("Launcher", "App widget binding finished");
	}

	public void finishBindingSamsungWidgets() {
		Log.d("Launcher", "Samung widget binding finished");
	}

	public void finishBindingShortcuts() {
		Log.d("Launcher", "Workspace shortcut binding finished");
	}

	public int getCurrentWorkspaceScreen() {
		return getScreen();
	}

	/**
	 * 完整
	 */
	public boolean isAllAppsVisible() {
		if (this.mMenuManager != null) {
			return this.mMenuManager.isOpened();
		}

		return false;
	}

	public void startBinding() {
		Log.d(TAG, "Launcher binding started");
		getLocalActivityManager().removeAllActivities();
		this.mDesktopItems.clear();

		int j = this.mWorkspace.getChildCount();
		int k = 0;

		while (k < j) {
			((ViewGroup) this.mWorkspace.getChildAt(k))
					.removeAllViewsInLayout();
			k++;
		}
	}

	/**
	 * 完整
	 */
	public void bindAppWidget(LauncherAppWidgetInfo paramLauncherAppWidgetInfo) {
		Workspace localWorkspace = this.mWorkspace;
		int j = paramLauncherAppWidgetInfo.appWidgetId;
		AppWidgetProviderInfo localAppWidgetProviderInfo = this.mAppWidgetManager
				.getAppWidgetInfo(j);

		if (localAppWidgetProviderInfo == null) {
			if (this.mConfigChange) {
				LauncherAppWidgetInfo localLauncherAppWidgetInfo = paramLauncherAppWidgetInfo;

				if (localLauncherAppWidgetInfo.hostView != null) {
					AppWidgetHostView localAppWidgetHostView1 = localLauncherAppWidgetInfo.hostView;
					int m = localLauncherAppWidgetInfo.screen;
					localWorkspace.removeInScreen(localAppWidgetHostView1, m);
				}
			}
		} else {
			AppWidgetHostView localAppWidgetHostView2 = this.mAppWidgetHost
					.createView(this, j, localAppWidgetProviderInfo);
			paramLauncherAppWidgetInfo.hostView = localAppWidgetHostView2;
			paramLauncherAppWidgetInfo.hostView.setAppWidget(j,
					localAppWidgetProviderInfo);
			paramLauncherAppWidgetInfo.hostView
					.setTag(paramLauncherAppWidgetInfo);

			AppWidgetHostView localAppWidgetHostView3 = paramLauncherAppWidgetInfo.hostView;
			int i2 = paramLauncherAppWidgetInfo.screen;
			int i3 = paramLauncherAppWidgetInfo.cellX;
			int i4 = paramLauncherAppWidgetInfo.cellY;
			int i5 = paramLauncherAppWidgetInfo.spanX;
			int i6 = paramLauncherAppWidgetInfo.spanY;
			localWorkspace.addInScreen(localAppWidgetHostView3, i2, i3, i4, i5,
					i6, false);
			localWorkspace.requestLayout();
			this.mDesktopItems.add(paramLauncherAppWidgetInfo);
		}
	}

	/**
	 * 完整
	 */
	private void unbindDesktopItems() {
		Iterator<ItemInfo> localIterator = this.mDesktopItems.iterator();

		while (localIterator.hasNext()) {
			((ItemInfo) localIterator.next()).unbind();
		}
	}

	View createShortcut(ShortcutInfo shortcutInfo) {
		Workspace localWorkspace = this.mWorkspace;
		int i = this.mWorkspace.getCurrentScreen();
		ViewGroup localViewGroup = (ViewGroup) localWorkspace.getChildAt(i);

		return createShortcut(R.layout.application, localViewGroup,
				shortcutInfo);
	}

	private static class LocaleConfiguration {
		public String locale;
		public int mcc = -1;
		public int mnc = -1;
	}

	private class RenameFolder {
		private EditText mInput;

		Dialog createDialog() {
			// mWaitingForResult = true;

			final View layout = View.inflate(Launcher.this,
					R.layout.rename_folder, null);
			mInput = (EditText) layout.findViewById(R.id.folder_name);

			AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this);
			builder.setIcon(0);
			builder.setTitle(getString(R.string.rename_folder_title));
			builder.setCancelable(true);
			builder.setOnCancelListener(new Dialog.OnCancelListener() {
				public void onCancel(DialogInterface dialog) {
					cleanup();
				}
			});
			builder.setNegativeButton(getString(R.string.cancel_action),
					new Dialog.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							cleanup();
						}
					});
			builder.setPositiveButton(getString(R.string.rename_action),
					new Dialog.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							changeFolderName();
						}
					});
			builder.setView(layout);

			final AlertDialog dialog = builder.create();
			dialog.setOnShowListener(new DialogInterface.OnShowListener() {
				public void onShow(DialogInterface dialog) {
					mWorkspace.lock();
				}
			});

			return dialog;
		}

		private void changeFolderName() {
			// final String name = mInput.getText().toString();
			// if (!TextUtils.isEmpty(name)) {
			// // Make sure we have the right folder info
			// mFolderInfo = sModel.findFolderById(mFolderInfo.id);
			// mFolderInfo.title = name;
			// LauncherModel.updateItemInDatabase(Launcher.this, mFolderInfo);
			//
			// if (mDesktopLocked) {
			// // mDrawer.lock();
			// sModel.loadUserItems(false, Launcher.this, false, false);
			// } else {
			// final FolderIcon folderIcon = (FolderIcon) mWorkspace
			// .getViewForTag(mFolderInfo);
			// if (folderIcon != null) {
			// folderIcon.setText(name);
			// getWorkspace().requestLayout();
			// } else {
			// mDesktopLocked = true;
			// // mDrawer.lock();
			// sModel.loadUserItems(false, Launcher.this, false, false);
			// }
			// }
			// }
			// cleanup();
			String str = this.mInput.getText().toString();

			if (!TextUtils.isEmpty(str)) {
				Launcher localLauncher1 = Launcher.this;
				HashMap localHashMap = mFolders;
				Long localLong = Long.valueOf(mFolderInfo.id);
				FolderInfo localFolderInfo1 = (FolderInfo) localHashMap
						.get(localLong);
				// FolderInfo localFolderInfo2 =
				// Launcher.access$1602(localLauncher1, localFolderInfo1);
				mFolderInfo = localFolderInfo1;
				Launcher.this.mFolderInfo.title = str;

				Launcher localLauncher2 = Launcher.this;
				FolderInfo localFolderInfo3 = Launcher.this.mFolderInfo;
				LauncherModel.updateItemInDatabase(localLauncher2,
						localFolderInfo3);

				if (!Launcher.this.mWorkspaceLoading) {
					Workspace localWorkspace = Launcher.this.mWorkspace;
					FolderInfo localFolderInfo4 = Launcher.this.mFolderInfo;
					FolderIcon localFolderIcon = (FolderIcon) localWorkspace
							.getViewForTag(localFolderInfo4);

					if (localFolderIcon != null) {
						localFolderIcon.setText(str);
						Launcher.this.getWorkspace().requestLayout();
					} else {
						Launcher.this.lockAllApps();

						// boolean bool = Launcher.access$1802(Launcher.this,
						// 1);
						LauncherModel localLauncherModel2 = mModel;
						Launcher localLauncher4 = Launcher.this;
						localLauncherModel2.startLoader(localLauncher4, false);
					}
				}

				Launcher.this.lockAllApps();

				LauncherModel localLauncherModel1 = mModel;
				Launcher localLauncher3 = Launcher.this;
				localLauncherModel1.startLoader(localLauncher3, false);
			}

			cleanup();
		}

		private void cleanup() {
			mWorkspace.unlock();
			dismissDialog(DIALOG_RENAME_FOLDER);
			mWaitingForResult = false;
			mFolderInfo = null;
		}
	}

	/**
	 * Displays the shortcut creation dialog and launches, if necessary, the
	 * appropriate activity.
	 */
	private class CreateShortcut implements DialogInterface.OnClickListener,
			DialogInterface.OnCancelListener,
			DialogInterface.OnDismissListener, DialogInterface.OnShowListener {

		private AddAdapter mAdapter;

		Dialog createDialog() {
			// Log.e(TAG,"mWaitingForResult true   55555");
			// mWaitingForResult = true;

			mAdapter = new AddAdapter(Launcher.this);

			final AlertDialog.Builder builder = new AlertDialog.Builder(
					Launcher.this);
			builder.setTitle(getString(R.string.menu_item_add_item));
			builder.setAdapter(mAdapter, this);

			builder.setInverseBackgroundForced(true);

			AlertDialog dialog = builder.create();
			dialog.setOnCancelListener(this);
			dialog.setOnDismissListener(this);
			dialog.setOnShowListener(this);

			return dialog;
		}

		public void onCancel(DialogInterface dialog) {
			mWaitingForResult = false;
			// Log.e(TAG,"mWaitingForResult false   66666");
			cleanup();
		}

		public void onDismiss(DialogInterface dialog) {
			mWorkspace.unlock();
			mWaitingForResult = false;
			// Log.e(TAG,"mWaitingForResult false   7777");
		}

		private void cleanup() {
			mWorkspace.unlock();
			dismissDialog(DIALOG_CREATE_SHORTCUT);
		}

		/**
		 * Handle the action clicked in the "Add to home" dialog.
		 */
		public void onClick(DialogInterface dialog, int which) {
			LogUtils.d(TAG, "CreateShortcut-onClick");

			Resources res = getResources();
			cleanup();

			switch (which) {
			case AddAdapter.ITEM_SHORTCUT: {
				// Insert extra item to handle picking application
				pickShortcut(REQUEST_PICK_SHORTCUT,
						R.string.title_select_shortcut);

				break;
			}

			case AddAdapter.ITEM_APPWIDGET: {
				int appWidgetId = Launcher.this.mAppWidgetHost
						.allocateAppWidgetId();

				Intent pickIntent = new Intent(
						AppWidgetManager.ACTION_APPWIDGET_PICK);
				pickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
						appWidgetId);

				// add the search widget
				ArrayList<AppWidgetProviderInfo> customInfo = new ArrayList<AppWidgetProviderInfo>();
				AppWidgetProviderInfo info = new AppWidgetProviderInfo();
				info.provider = new ComponentName(getPackageName(), "XXX.YYY");
				info.label = getString(R.string.group_search);
				info.icon = R.drawable.ic_search_widget;
				customInfo.add(info);
				pickIntent.putParcelableArrayListExtra(
						AppWidgetManager.EXTRA_CUSTOM_INFO, customInfo);

				ArrayList<Bundle> customExtras = new ArrayList<Bundle>();
				Bundle b = new Bundle();
				b.putString(EXTRA_CUSTOM_WIDGET, SEARCH_WIDGET);
				customExtras.add(b);
				pickIntent.putParcelableArrayListExtra(
						AppWidgetManager.EXTRA_CUSTOM_EXTRAS, customExtras);
				// start the pick activity
				startActivityForResult(pickIntent, REQUEST_PICK_APPWIDGET);

				break;
			}

			case AddAdapter.ITEM_LIVE_FOLDER: {
				// Insert extra item to handle inserting folder
				Bundle bundle = new Bundle();

				ArrayList<String> shortcutNames = new ArrayList<String>();
				shortcutNames.add(res.getString(R.string.group_folder));
				bundle.putStringArrayList(Intent.EXTRA_SHORTCUT_NAME,
						shortcutNames);

				ArrayList<ShortcutIconResource> shortcutIcons = new ArrayList<ShortcutIconResource>();
				shortcutIcons.add(ShortcutIconResource.fromContext(
						Launcher.this, R.drawable.ic_launcher_folder));
				bundle.putParcelableArrayList(
						Intent.EXTRA_SHORTCUT_ICON_RESOURCE, shortcutIcons);

				Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
				pickIntent.putExtra(Intent.EXTRA_INTENT, new Intent(
						LiveFolders.ACTION_CREATE_LIVE_FOLDER));
				pickIntent.putExtra(Intent.EXTRA_TITLE,
						getText(R.string.title_select_live_folder));
				pickIntent.putExtras(bundle);

				startActivityForResult(pickIntent, REQUEST_PICK_LIVE_FOLDER);

				break;
			}

			case AddAdapter.ITEM_WALLPAPER: {
				startWallpaper();
				break;
			}
			}
		}

		public void onShow(DialogInterface dialog) {
			mWorkspace.lock();
		}
	}

	/**
	 * Receives notifications when applications are added/removed.
	 */
	private class CloseSystemDialogsIntentReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			closeSystemDialogs();
		}
	}

	/**
	 * Receives notifications whenever the appwidgets are reset.
	 */
	private class AppWidgetResetObserver extends ContentObserver {
		/**
		 * Creates a new AppWidgetResetObserver object.
		 */
		public AppWidgetResetObserver() {
			super(new Handler());
		}

		@Override
		public void onChange(boolean selfChange) {
			Launcher.this.onAppWidgetReset();
		}
	}

	class WallpaperFastBitmapDrawable extends Drawable {
		private int mDrawLeft;
		private int mDrawTop;
		private final int mHeight;
		private final int mWidth;
		private Bitmap mBitmap;

		/**
		 * Creates a new WallpaperFastBitmapDrawable object.
		 * 
		 * @param bitmap
		 */
		private WallpaperFastBitmapDrawable(Bitmap bitmap) {
			this.mBitmap = bitmap;
			this.mWidth = bitmap.getWidth();
			this.mHeight = bitmap.getHeight();

			int k = this.mWidth;
			int m = this.mHeight;
			setBounds(0, 0, k, m);
		}

		public void draw(Canvas paramCanvas) {
			Bitmap localBitmap = mBitmap;
			float f1 = this.mDrawLeft;
			float f2 = this.mDrawTop;
			paramCanvas.drawBitmap(localBitmap, f1, f2, null);
		}

		public int getIntrinsicHeight() {
			return this.mHeight;
		}

		public int getIntrinsicWidth() {
			return this.mWidth;
		}

		public int getMinimumHeight() {
			return this.mHeight;
		}

		public int getMinimumWidth() {
			return this.mWidth;
		}

		public int getOpacity() {
			return -1;
		}

		public void setAlpha(int paramInt) {
			throw new UnsupportedOperationException(
					"Not supported with this drawable");
		}

		public void setBounds(int paramInt1, int paramInt2, int paramInt3,
				int paramInt4) {
			int i = paramInt3 - paramInt1;
			int j = this.mWidth;
			int k = ((i - j) / 2) + paramInt1;
			this.mDrawLeft = k;

			int m = paramInt4 - paramInt2;
			int n = this.mHeight;
			int i1 = ((m - n) / 2) + paramInt2;
			this.mDrawTop = i1;
		}

		public void setBounds(Rect paramRect) {
			super.setBounds(paramRect);
		}

		public void setColorFilter(ColorFilter paramColorFilter) {
			throw new UnsupportedOperationException(
					"Not supported with this drawable");
		}

		public void setDither(boolean paramBoolean) {
			throw new UnsupportedOperationException(
					"Not supported with this drawable");
		}

		public void setFilterBitmap(boolean paramBoolean) {
			throw new UnsupportedOperationException(
					"Not supported with this drawable");
		}
	}

	class TextDialog implements DialogInterface.OnDismissListener,
			DialogInterface.OnShowListener {
		int mId;

		/**
		 * Creates a new TextDialog object.
		 */
		private TextDialog() {
		}

		private void cleanup() {
			Launcher.mUninstallPackageName = null;

			// boolean bool = Launcher.access$1402(Launcher.this, 0);
			// int i = Launcher.access$2602(Launcher.this, -1);
		}

		Dialog createDialog(int id) {
			this.mId = id;

			AlertDialog.Builder localBuilder1 = new AlertDialog.Builder(
					Launcher.this);
			if (id == DIALOG_DELETE_APPLICATION) {
				localBuilder1.setIcon(android.R.drawable.ic_dialog_alert);
				localBuilder1
						.setTitle(getString(R.string.Delete_homescreen_application));
				localBuilder1.setMessage(R.string.application_delete);
			}

			while (true) {
				localBuilder1.setCancelable(true);
				localBuilder1.setOnCancelListener(new OnCancelListener() {
					public void onCancel(DialogInterface dialog) {
						Launcher.this.cancelRemovePage();

						// Launcher.TextDialog.access$2400(this.this$1);
					}
				});

				String str2 = Launcher.this.getString(R.string.cancel_action);
				localBuilder1.setNegativeButton(str2, new OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						int i = TextDialog.this.mId;

						if (i == DIALOG_DELETE_WORKSCREEN) {
							Launcher.this.cancelRemovePage();
						} else {
						}

						// while (true)
						// {
						// Launcher.TextDialog.access$2400(this.this$1);
						// return;
						// if (i != 4)
						// continue;
						// Launcher.access$2500(this.this$1.this$0).invalidate();
						// }
					}
				});

				String str3 = Launcher.this.getString(R.string.rename_action);
				// Launcher.TextDialog.3 local3 = new
				// Launcher.TextDialog.3(this);
				localBuilder1.setPositiveButton(str3, new OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						int i = TextDialog.this.mId;

						if (i == DIALOG_DELETE_APPLICATION) {
							Launcher.this.uninstallPackage();

							// Launcher.TextDialog.access$2400(this.this$1);
						}

						if (i == DIALOG_DISCARD_MENUEDIT) {
							Launcher.this.menudiscard();

							// Launcher.TextDialog.access$2400(this.this$1);
						}

						if (i == DIALOG_DELETE_WORKSCREEN) {
							Launcher.this.removePage();
						}
					}
				});

				if (id == DIALOG_DISCARD_MENUEDIT) {
					localBuilder1.setMessage(R.string.menuedit_discard);
				}

				if (id == DIALOG_DELETE_WORKSCREEN) {
					localBuilder1.setMessage(R.string.workscreen_delete);
				}

				AlertDialog localAlertDialog = localBuilder1.create();
				localAlertDialog.setOnShowListener(this);
				localAlertDialog.setOnDismissListener(this);
				return localAlertDialog;
			}
		}

		public void onDismiss(DialogInterface paramDialogInterface) {
		}

		public void onShow(DialogInterface paramDialogInterface) {
			// boolean bool = Launcher.access$1402(Launcher.this, 1);
		}
	}

	class PackageDeleteObserver extends IPackageDeleteObserver.Stub {

		public void packageDeleted(boolean succeeded) {
			// Log.e(TAG,"PackageDeleteObserver  "+succeeded);
			Message localMessage = Launcher.this.mHandler
					.obtainMessage(SUCCEEDED);
			int i;
			if (succeeded) {
				i = 1;
			} else {
				i = 0;
			}
			localMessage.arg1 = i;
			Launcher.this.mHandler.sendMessage(localMessage);
			return;
		}
	}

	public IconCache getIconCache() {
		return mIconCache;
	}
}
